Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sort function that returns the keys

Javascript has an inbuilt sort method for arrays.

What I need, is the keys of the array, not the values. I don't want the array to be modified. Is there an obvious way to get those keys (before I start writing my own sort...)?

example:

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

But what I want to know is

keys = [1,2,0] ; 

So I can use it like this:

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

Thanks for helping so fast. All of you.

like image 584
Emmanuel Delay Avatar asked Apr 10 '26 02:04

Emmanuel Delay


2 Answers

Try this code:

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];
like image 149
Dmitri Pavlutin Avatar answered Apr 12 '26 17:04

Dmitri Pavlutin


You may have a look here: 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>');
like image 29
Nina Scholz Avatar answered Apr 12 '26 15:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!