javascript排序稀疏数组保持索引 [英] javascript sort sparse array keep indexes
本文介绍了javascript排序稀疏数组保持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对稀疏数组进行排序并将元素保留在相同索引上的最佳方法是什么?
例如:
What is the best method to sort a sparse array and keep the elements on the same indexes? For example:
a[0] = 3,
a[1] = 2,
a[2] = 6,
a[7] = 4,
a[8] = 5,
我希望在排序之后
a[0] = 2,
a[1] = 3,
a[2] = 4,
a[7] = 5,
a[8] = 6.
推荐答案
这是一种方法。它将已定义的数组元素复制到新数组并保存其索引。它对新数组进行排序,然后将排序后的结果放回以前使用过的索引中。
Here's one approach. It copies the defined array elements to a new array and saves their indexes. It sorts the new array and then puts the sorted results back into the indexes that were previously used.
var a = [];
a[0] = 3;
a[1] = 2;
a[2] = 6;
a[7] = 4;
a[8] = 5;
// sortFn is optional array sort callback function,
// defaults to numeric sort if not passed
function sortSparseArray(arr, sortFn) {
var tempArr = [], indexes = [];
for (var i = 0; i < arr.length; i++) {
// find all array elements that are not undefined
if (arr[i] !== undefined) {
tempArr.push(arr[i]); // save value
indexes.push(i); // save index
}
}
// sort values (numeric sort by default)
if (!sortFn) {
sortFn = function(a,b) {
return(a - b);
}
}
tempArr.sort(sortFn);
// put sorted values back into the indexes in the original array that were used
for (var i = 0; i < indexes.length; i++) {
arr[indexes[i]] = tempArr[i];
}
return(arr);
}
工作演示: http://jsfiddle.net/jfriend00/3ank4/
这篇关于javascript排序稀疏数组保持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文