Bryan
Bryan

Reputation: 3009

find() vs map() in JavaScript

Say I have the following array, and I want to change the value of a property inside one of the objects:

var array = [{id: 1, exampleBoolean: false}, {id: 2, exampleBoolean: false}];

I've always used map for something like this, but I saw someone use find instead and am curious if that is a legitimate way to do it? The following functions both technically work (at least in Chrome), but I want to know if they're both technically "correct". Reading docs, my interpretation is that you should use map, but it isn't 100% clear to me whether or not I am right.

With find:

changeValueWithFind(id: number) {
  array.find(item => item.id === id).exampleBoolean = true;
}

With map:

changeValueWithMap(id: number) {
    array = array.map(item => {
      if (item.id === id) {
        return {
          ...item,
          exampleBoolean: true,
        }
      }
      return item;
    });
  }

Upvotes: 2

Views: 12665

Answers (2)

Daniel Duarte
Daniel Duarte

Reputation: 494

Actually using map() in this case would be an anti-pattern. map() is intended to be used to generate a new array processing individually each of the elements in the original one, and not modifying them. In order to go through the elements modifying them I'd recommend forEach instead.

The solution with find() in this case is cleaner, but also take into account that find() could return undefined in case the element is not found.

That way, your example could be modified to:

changeValueWithFind(id: number) {
  const myElem = array.find(item => item.id === id);
  if (myElem) {
    myElem.exampleBoolean = true
  }
}

Upvotes: 4

Or Hasson
Or Hasson

Reputation: 21

In my opinion in that case you need use the find(). Doesn’t see any reason to use map() here.

When to use map? .map() when you want to transform elements in an array. When to use find? .find() When you want to select a single element from an array.

More essential info:

https://medium.com/@JeffLombardJr/understanding-foreach-map-filter-and-find-in-javascript-f91da93b9f2c

Upvotes: 1

Related Questions