15

Is it possible to map an array to a new array and to sort it at the same time without iterating twice (once for the map on the first array and once for the sort on the second array)? I've been trying to sort it with an anonymous function when using the map method like this:

var arr=[4,2,20,44,6];
var arr2=arr.map(function(item, index, array){
    if(index==array.length-1 || item==array[index+1]){
        return item;
    }
    else if((item-array[index+1])<0){
        return item;
    }
    else if((item-array[index+1])>0){
        return array[index+1];
    }
});
console.log(arr2);

but it doesn't seem to work. Am I way off base here in how I'm trying to implement this, or is there just a problem with my code?

2 Answers 2

23

Sorting generally takes more than one iteration by itself. It's almost certainly O(n log n) for the average case (the algorithm isn't specified by ECMAScript, but that's the best you can do with a comparison sort), so there's not much point in doing both at the same time.

You can chain them into one expression though, since sort returns the array itself:

function order(a, b) {
    return a < b ? -1 : (a > b ? 1 : 0);
}
var arr2 = arr.map(function(item) { ... }).sort(order);
Sign up to request clarification or add additional context in comments.

Comments

0

As of ECMAScript 2023 there is a native method for this: toSorted:

const arr = [4, 2, 20, 44, 6];
const arr2 = arr.toSorted((a, b) => a - b); // sort numerically
console.log("unsorted", ...arr);
console.log("  sorted", ...arr2);

Comments

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.