Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between filter and map in jquery

What is the difference between map() and filter() in jQuery?

Kindly differentiate between the two in simple words.

like image 764
ShivamRajput Avatar asked Nov 28 '22 22:11

ShivamRajput


2 Answers

You've asked about map and filter "in jQuery." jQuery does have map and filter, and separately, JavaScript arrays have map and filter. Their purposes and uses are similar, although sadly the information they give their callbacks is different.

filter is for taking a jQuery object or array and producing a new jQuery object or array that only contains a subset of the entries in the original — that is, we apply a filter to it, getting only the entries that match the filter. So the result will be the same size (if you don't remove anything) or smaller, but never larger, and will only have entries from the original.

map is for taking a jQuery object or array and producting a new jQuery object or array with new, different entries based on the entries in the original. The result will always be the same size as the original, but the entries in the result could be completely different from the original's.

So as you can see, they do different things: filter produces a subset of the entries from the original, while map produces a result of the same size as the original but with (potentially) completely different contents.

Both of them can use callbacks (map always does). What those callbacks do is very different, though: filter's callback decides whether to keep the entry: It returns a flag where any truthy* value means "keep the entry," and any falsy* value means "remove it." But map's callback returns the actual entry to use in the resulting jQuery object or array.

You've asked specifically about jQuery, so let's take a jQuery example to start with, see comments:

// Let's get all the divs inside our #example div
var divs = $("#example div");
console.log("total divs: " + divs.length);

// `filter` lets us take that set of elements and filter out some;
// let's keep only the ones with the class `b`, using the ability
// of jQuery's `filter` to accept a CSS selector
var withb = divs.filter(".b");
console.log("divs with class b: " + withb.length);

// We could have used a callback function instead:
var withb2 = divs.filter(function() {
  // We return a "truthy" value to keep this entry, or a "falsy"
  // one to remove it
  return $(this).hasClass("b");
});
console.log("divs with class b: " + withb2.length);

// `map` lets us create a new jQuery object with completely different
// contents, where each entry is derived from the original entry.
// Let's get a jQuery object containing the `data-foo` value of each
// entry in our divs. The result will be the same size as the original,
// but will have entirely different contents.
var foos = divs.map(function() {
  return $(this).attr("data-foo");
});
console.log("foos.length: " + foos.length);
console.log("foos: " + foos.get().join(", "));
<div id="example">
  <div data-foo="1" class="a b">I'm .a.b</div>
  <div data-foo="2" class="a">I'm .a</div>
  <div data-foo="3" class="b">I'm .b</div>
  <div data-foo="4" class="a b">I'm .a.b</div>
  <div data-foo="5" class="a">I'm .a</div>
  <div data-foo="6" class="b">I'm .b</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Notice how map let us create a jQuery object whose contents were not DOM elements. 99.999% of the time, jQuery objects contain DOM elements and most jQuery methods expect that the object contains DOM elements. But you can create jQuery objects with other things (like our strings above from data-foo). Typically it's rare, and you almost always end up using get() on the result to get a plain array of those values.

Normally with jQuery's map and filter, you use this within the callback. It refers to the current entry in the jQuery object. They also receive arguments such as the index of the entry in the jQuery object, see the documentation for details. Note that the arguments jQuery passes its map and filter functions are different from the arguments JavaScript passes its map and filter functions.

Speaking of which...


JavaScript arrays also have map and filter. Conceptually they do the same thing as jQuery's. Let's take a look:

// Say I have
var array = [1, 2, 3, 4, 5, 6];

// I can use `filter` to get an array of just odd numbers:
var odds = array.filter(function(entry) { return entry % 2 == 1; });
console.log("odds: " + odds);

// I can use `map` to get an array of those numbers doubled:
var doubles = array.map(function(entry) { return entry * 2; });
console.log("doubles: " + doubles);

* "truthy" and "falsy": A value that coerces to true when used as a boolean is a "truthy" value; one that coerces to false is a "falsy" one. The falsy values in JavaScript are 0, NaN, null, undefined, "", and of course, false. All other values are truthy.

like image 117
T.J. Crowder Avatar answered Dec 09 '22 22:12

T.J. Crowder


filter() is used to skip unwanted elements of collection. map() is used to modify elements of collection.

filter() may return collection with less elements then in original collection. It may even return empty collection. map() will always return collection with the same number of elements.

Both filter() and map() will require as an argument a function that do something with single element of collection.

What is different is that filter() expects that function to return Boolean value based on which element will be skipped or not. map() will expect that function to return an new collection element.

filter(), map() and quite a few others (e.g. reduce()) exist because of observation that a lot of collection manipulating algorithms can be split into two separate behaviors. One is doing something to element, and other is making sure that something is done to all elements in a collection.

Hope that helps.

like image 43
przemo_li Avatar answered Dec 09 '22 23:12

przemo_li