首页 > 解决方案 > 获取数组编号的数组

问题描述

我有一个像这样的数组:

let array = [14, 42, 1, 3]

我想将数组编号映射到这个:

[1, 0, 3, 2]

原因如下:

到目前为止我已经尝试过:

let sort = (array) => {
  let result = []
  let x = array.slice(0).sort((a, b) => b - a)
  for (let elem of x) {
    result.push(array.indexOf(elem))
  }
  console.log(result)
}

// Working
sort([14, 42, 1, 3]) // [1, 0, 3, 2]

// Not working, includes the index "0" two times
sort([14, 42, 14, 3]) // [1, 0, 0, 3]
// Expected: [1, 0, 2, 3]

标签: javascriptarrays

解决方案


您可以通过从给定数组中获取值来获取索引并对其进行排序。

const sort = array => [...array.keys()].sort((a, b) => array[b] - array[a]);

console.log(sort([14, 42, 1, 3]));
console.log(sort([14, 42, 14, 3]));


推荐阅读