Map and sort on one iteration in Javascript?

Is it possible to match an array with a new array and sort it at the same time without repeating twice (once for a map in the first array and once for sorting in the second array)? I am trying to sort it with an anonymous function when using the map method as follows:

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 does not seem to work. Am I somehow outside the base here, how am I trying to implement this, or is there only a problem with my code?

+3
source share
2 answers

. O (n log n) ( ECMAScript, , ), .

, sort :

function order(a, b) {
    return a < b ? -1 : (a > b ? 1 : 0);
}
var arr2 = arr.map(function(item) { ... }).sort(order);
+2

, , . ?

0

Source: https://habr.com/ru/post/1735308/


All Articles