javascript - 获取数组编号的数组
问题描述
我有一个像这样的数组:
let array = [14, 42, 1, 3]
我想将数组编号映射到这个:
[1, 0, 3, 2]
原因如下:
1
: 因为14
是第二大数字0
: 因为42
是最大的数3
: ...
到目前为止我已经尝试过:
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]
解决方案
您可以通过从给定数组中获取值来获取索引并对其进行排序。
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]));
推荐阅读
- elasticsearch - 从查询中删除停用词
- sql - 如何使用旧列的别名对新创建的列进行分组?
- sql-server - Sql Studio (v17) 有哪些新的登录选项,例如“Active Directory - 集成”
- c# - 如何在有关系的两个类之间添加在下拉列表中获取数据的可能性?
- javascript - 环回查询mongodb文档
- javascript - 为什么进度条不可见?
- c# - 在 EF 查询中使用字符串变量而不是文字时出现问题
- django - Django 子查询只返回第一个元素
- javascript - 用于许多节点的 Dijkstra / 性能改进
- c++ - 编译器找不到 .h 文件(代码块)