我有一个按以下方式排序的数组
var items = [2.99, 5.99, 23.99, 1.99];
items.sort(function(a,b) { return a - b;});
输出如下:
[1.99, 2.99, 5.99, 23.99]
但我需要一种方法对其进行排序,但保留原始索引的索引,例如
[3: 1.99, 0: 2.99, 1: 5.99, 2:23.99]
如有任何帮助,我们将不胜感激。
最佳答案
将其映射到对象数组。
因此,在生成的数组中,每个成员都是一个对象,具有保存数字的 n
属性和保存原始索引的 i
属性。
然后您可以像平常一样迭代该数组并获取数据。
var items = [2.99, 5.99, 23.99, 1.99];
var arr_of_objs = items.map(function(n, i) {
return { n:n, i:i };
}).sort(function(a, b) {
return a.n - b.n;
});
arr_of_objs.forEach(function(obj, i) {
this.textContent += "number: " + obj.n + ", orig idx: " + obj.i + ", new idx: " + i + "\n";
}, document.querySelector("pre"));
<pre></pre>
关于javascript - 将数组转换为对象并保存原始索引字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26089394/