Reputation: 690
in javascript I have next array:
var a = [0, 2, 1, 3];
Where this array index>value pair is:
0 = 0, 1 = 2, 2 = 1, 3 = 3
What is simplest and most elegant way of keeping array index numbers after sorting an array. After sort() index>value pair should be like this:
0 = 0, 2 = 1, 1 = 2, 3 = 3
.. but I should be able to display those sorted values. Problem is that array cannot list by jumping index position 0, 2, 1, 3 but only as 0, 1, 2, 3.
Can I somehow make a new array whose array values will be those new index positions, and then sort this new array but keep memorized former index>value pairs.
Although it sound simple I cannot find solution to this.
Thanks
P.S. I actually want to sort by number of spaces between words in phrases contained in array. Then I want to display sorted by the number of spaces (phrases with most words first).
var input = ["zero", "here two spaces", "none", "here four spaces yes"];
var resort = [];
for (i = 0; i < input.length; i++) {
var spaces = (input[i].split(" ").length - 1);
resort.push(spaces); // new array with number of spaces list
}
Upvotes: 4
Views: 3360
Reputation: 324630
If you want to sort by something nontrivial, pass a callback to sort
.
input.sort(function(a,b) {
// b - a for descending order
return b.split(" ").length - a.split(" ").length;
});
Upvotes: 1
Reputation: 386570
You could use Sorting with map with a new array which keeps the original indices and values.
// the array to be sorted
var list = [0, 2, 1, 3];
// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
return { index: i, value: el };
})
// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
return a.value - b.value;
});
// container for the resulting order
var result = mapped.map(function(el){
return list[el.index];
});
console.log(result);
console.log(mapped);
.as-console-wrapper { max-height: 100% !important; top: 0; }´
Upvotes: 5