[removed] Sort array and return an array of indicies that indicates the position of the sorted elements with respect to the original elements

后端 未结 8 799
囚心锁ツ
囚心锁ツ 2020-12-05 01:51

Suppose I have a Javascript array, like so:

var test = [\'b\', \'c\', \'d\', \'a\'];

I want to sort the array. Obviously, I can just do th

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 02:20

    You can do this with the Map object. Just set the key/value as index/value and use the Array.from to get the Iterator as a bi-dimensional array then sort either the indexes, the values or both.

    function sorting(elements) {
      const myMap = new Map();
      elements.forEach((value, index) => {
        myMap.set(index, value);
      });
      const arrayWithOrderedIndexes = Array.from(myMap.entries()).sort((left, right) => {return left[1] < right[1] ? -1 : 1});
      myMap.clear();
      return arrayWithOrderedIndexes.map(elem => elem[0]);
    }
    const elements = ['value','some value','a value','zikas value','another value','something value','xtra value'];
    sorting(elements);
    

提交回复
热议问题