4

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
}
0

2 Answers 2

5

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; }´

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your kind help.
1

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;
});

2 Comments

Hey @ Niet, this works perfectly! And it's simple too. Unfortunately I cannot give you my vote due to the my fresh reputation. Many thanks.
@Dan, you can try now:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.