zloctb zloctb - 4 months ago 11
Javascript Question

What's difference between find() and indexOf() methods for array

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';

Answer

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

Comments