-1

Best way to find if an item is in a JavaScript array?

var array = [2, 5, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1


let found = array.find(x => x === 5 );
console.log(found); //5

found = array.find(x => x === 51 );
console.log(found); //undefined

What method use to detect value in array ?

array.indexOf(val) !== -1 or

typeof array.find(x => x === val ) !== 'undefined';
Community
  • 1
  • 1
zloctb
  • 10,592
  • 8
  • 70
  • 89

3 Answers3

3

The difference comes when you have array of objects.

Sample

var d = [
  {a:1, b: "test"},
  {a:2, b: "test"},
  {a:3, b: "test"},
  {a:4, b: "test"},
  {a:5, b: "test"},
];
  
var r = d.find(x=> x.a===5);
console.log(r)

In such case, .indexOf will not be feasible.

Also, array.find will return matched element but indexOf will return the index of matched element.

Also, if the objective is to check if value exists in array, you can even look into Array.some

Sample

var d = [
  {a:1, b: "test"},
  {a:2, b: "test"},
  {a:3, b: "test"},
  {a:4, b: "test"},
  {a:5, b: "test"},
];
  
var r = d.some(x=> x.a===5);
console.log(r)

References

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

Array#find returns the item itself and Array#indexOf the index of the item.

With Array#find, you have to check for undefined, which is misleading if the value you are looking for is undefined. In this case, I suggest to use Array#indexOf, where you can check if the value is not in the array, because of the return value of -1 which is no valid index.

If you works on a system without ES6, you have to use Array#indexOf.

In your case, to get just a confirmation if the value is in the array, you may use Array#includes (ES6), which returns a boolen value.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

As per the official MDN documentation,

The find() method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.

Whereas,

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

In conclusion, each method is intended for its own dedicated use.

cassi.lup
  • 1,261
  • 7
  • 23