Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map and Sort in one iteration in Javascript?

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?

like image 635
Yansky Avatar asked Mar 03 '10 20:03

Yansky


People also ask

Can JavaScript filter and Map together?

JavaScript's Array#map() and Array#filter() functions are great when used together because they allow you to compose simple functions. For example, here's a basic use case for filter() : filtering out all numbers that are less than 100 from a numeric array. This function works fine on an array of numbers.

Can Map be sorted in JavaScript?

Use the sort() method to sort the keys in a Map, e.g. const sorted = new Map([... map1]. sort()) . The spread syntax (...) is used to get an array of the Map's entries, which we can sort using the sort method.

Does JavaScript Map maintain insertion order?

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

How do I iterate through a Map in JavaScript?

Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.


1 Answers

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);
like image 132
Matthew Crumley Avatar answered Oct 01 '22 22:10

Matthew Crumley