241

In jQuery, the map and each functions seem to do the same thing. Are there any practical differences between the two? When would you choose to use one instead of the other?

bendewey
  • 39,709
  • 13
  • 100
  • 125
dthrasher
  • 40,656
  • 34
  • 113
  • 139
  • See also: http://stackoverflow.com/questions/3612320/why-are-jquerys-callback-arguments-inconsistent – ryenus Sep 27 '16 at 12:57

6 Answers6

280

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});
// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array. For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5) 
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]

You'll also note that the this is not mapped in the map function. You will have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.

map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});
bendewey
  • 39,709
  • 13
  • 100
  • 125
  • 23
    Wrong, map isn't meant to change the supplied array, it's meant to return a *new* array based on the input array and the mapping function. – arul Apr 14 '09 at 19:57
  • 5
    @Seb, read my link to the each function, second paragraph jQuery.each function is not the same as $().each(). – bendewey Apr 14 '09 at 20:02
  • 4
    Also map() flattens returned arrays – George Mauer Jun 10 '11 at 19:38
  • 2
    when to use map and each. What are the performance benefits of both? – jason Jun 21 '13 at 17:38
  • 6
    @DaveVandenEynde if you want to break in the middle of the loop using `return false;` – Vigneshwaran Sep 19 '13 at 09:59
  • 1
    .each() is meant to be an mutable (not immutable) iterator. Map is an immutable iterator, because it returns a new array instead of changing the original array. – depiction Sep 05 '16 at 23:56
  • You would use $.each() just like a regular .forEach loop, but the syntax is much easier to read. You use map when you need to create a NEW array with modified array items. Which is great but might lead to memory issues. – Maria Blair Oct 16 '18 at 17:01
94

1: The arguments to the callback functions are reversed.

.each()'s, $.each()'s, and .map()'s callback function take the index first, and then the element

function (index, element) 

$.map()'s callback has the same arguments, but reversed

function (element, index)

2: .each(), $.each(), and .map() do something special with this

each() calls the function in such a way that this points to the current element. In most cases, you don't even need the two arguments in the callback function.

function shout() { alert(this + '!') }

result = $.each(['lions', 'tigers', 'bears'], shout)

// result == ['lions', 'tigers', 'bears']

For $.map() the this variable refers to the global window object.

3: map() does something special with the callback's return value

map() calls the function on each element, and stores the result in a new array, which it returns. You usually only need to use the first argument in the callback function.

function shout(el) { return el + '!' }

result = $.map(['lions', 'tigers', 'bears'], shout)

// result == ['lions!', 'tigers!', 'bears!']
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167
  • `function shout() { alert(this + '!') } result = $.each(['lions', 'tigers', 'bears'], shout)` producing a wrong result it contradicts your answer!! https://jsfiddle.net/9zy2pLev/ – Hemant Apr 04 '17 at 17:10
  • @Hemant Just tested the fiddle in Chrome and it seems to work fine. There are three alert dialogs ('lions!', 'tigers!', 'bears!') and at the end `result === ['lions', 'tigers', 'bears']` – Patrick McElhaney Apr 05 '17 at 20:48
22

The each function iterates over an array, calling the supplied function once per element, and setting this to the active element. This:

function countdown() {
    alert(this + "..");
}

$([5, 4, 3, 2, 1]).each(countdown);

will alert 5.. then 4.. then 3.. then 2.. then 1..

Map on the other hand takes an array, and returns a new array with each element changed by the function. This:

function squared() {
    return this * this;
}

var s = $([5, 4, 3, 2, 1]).map(squared);

would result in s being [25, 16, 9, 4, 1].

Magnar
  • 28,550
  • 8
  • 60
  • 65
18

i understood it by this:

function fun1() {
    return this + 1;
}
function fun2(el) {
    return el + 1;
}

var item = [5,4,3,2,1];

var newitem1 = $.each(item, fun1);
var newitem2 = $.map(item, fun2);

console.log(newitem1); // [5, 4, 3, 2, 1] 
console.log(newitem2); // [6, 5, 4, 3, 2] 

so, "each" function returns the original array while "map" function returns a new array

Till
  • 1,097
  • 13
  • 13
1
var intArray = [1, 2, 3, 4, 5];
//lets use each function
$.each(intArray, function(index, element) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2. Breaks the loop as soon as it encountered number 3
});

//lets use map function
$.map(intArray, function(element, index) {
  if (element === 3) {
    return false;
  }
  console.log(element); // prints only 1,2,4,5. skip the number 3.
});
Aamir Shaikh
  • 83
  • 1
  • 4
0

Jquery.map makes more sense when you are doing work on arrays as it performs very well with arrays.

Jquery.each is best used when iterating through selector items. Which is evidenced in that the map function does not use a selector.

$(selector).each(...)

$.map(arr....)

as you can see, map is not intended to be used with selectors.

Jeremy B.
  • 9,168
  • 3
  • 45
  • 57
  • 2
    the unfortunately named each function... Not the first time, and not the last that I'll get tripped up on which one someone is asking about – Jeremy B. Apr 14 '09 at 20:09
  • 8
    map and each both have a selector-version, and a util-version. $.map and $.each vs $("").map and $("").each. – Magnar Apr 14 '09 at 20:10