返回键的javascript sort函数

时间:2016-03-25 13:11:23

标签: javascript sorting

Javascript对数组有一个内置的排序方法。

我需要的是数组的键,而不是值。我不希望修改数组。 是否有明显的方法来获取这些密钥(在我开始编写自己的排序之前......)?

示例:

var fruit = ["pear", "apple", "lemon"];
fruit.sort();
// now fruit is ["apple", "lemon", "pear"];

但我想知道的是

keys = [1,2,0] ; 

所以我可以这样使用它:

var fruit = ["pear", "apple", "lemon"]; 
var keys = keysOfSortedArray(fruit);
for(var i in keys) {
  console.log(fruit[key[i]]);
}

感谢您的帮助如此之快。你们所有人。

4 个答案:

答案 0 :(得分:1)

在排序

之前,您需要备份(不是深度,浅层备份)
var fruit = ["pear", "apple", "lemon"]; 
var backup = fruit.slice();
fruit.sort();
var output = fruit.map(function(val){ return backup.indexOf(val) });

您的功能keysOfSortedArray将为

function keysOfSortedArray(arr)
{
    var backup = arr.slice();
    backup.sort();
    return backup.map(function(val){ return arr.indexOf(val) });
}

答案 1 :(得分:1)

试试这段代码:

var fruit = ["pear", "apple", "lemon"];
var sorted = [].concat(fruit).sort();

var sortedIndex = sorted.map(function(item) { 
   return fruit.indexOf(item)
});
console.log(sortedIndex) // prints [1, 2, 0];

答案 2 :(得分:1)

您可以在这里查看:Sorting with map



// the array to be sorted
var fruit = ["pear", "apple", "lemon"];

// temporary array holds objects with position and sort-value
var mapped = fruit.map(function (el, i) {
    return { index: i, value: el.toLowerCase() };
})

// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
    return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// container for the resulting order
var result = mapped.map(function (el) {
    return fruit[el.index];
});

// get the wanted keys
var keys = mapped.map(function (el) {
    return el.index;
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这有效:

<强> ES5

function sortIndexes (a) {
    var aClone = a.slice(0);
    return a.sort().map(function(x){
        return aClone.indexOf(x);
    });
}

var fruit = ["pear", "apple", "lemon"];
console.log(sortIndexes(fruit));

使用原型 ES5

Array.prototype.sortIndexes = function () {
    var aClone = this.slice(0); 
    return this.sort().map(function (x) {
        return aClone.indexOf(x);
    });
};

var fruit = ["pear", "apple", "lemon"];
console.log(fruit.sortIndexes());

ES6 (很多美女)

let sortIndexes = (a) => {
    var aClone = a.slice(0);
    return a.sort().map(x => aClone.indexOf(x));
}


let fruit = ["pear", "apple", "lemon"];
console.log(sortIndexes(fruit));

使用原型 ES6 (非常美丽和更好):

Array.prototype.sortIndexes = function(){
    let aClone = this.slice(0); 
    return this.sort().map(x => aClone.indexOf(x));
}

let fruit = ["pear", "apple", "lemon"];
console.log(fruit.sortIndexes());