Skip to content
GitHub Twitter

Find a value in JavaScript array

Find a value in JavaScript array

Following are the ways to find in a javascript array.

Using Array.find()

The recommended solution is to use the find() method that returns the first occurrence of an element in the array that satisfies the given condition or predicate. The find() method takes a callback function as parameter and executes that function once for each element present in the array, until it finds one where the function returns a true value.

If the element is found it returns the value of the element, otherwise undefined is returned. The following code example demonstrates this by finding a person with the name John:

var obj = [
    {name: 'Max', age: 23},
    {name: 'John', age: 20},
    {name: 'Caley', age: 18}
];

var found = obj.find(e => e.name === 'John');
console.log(found); // { name: 'John', age: 20 }

The return value may sound a little confusing. The theory says that it returns the element whereas in the code a true value is returned on success. The reason is that the true value is used internally. The true value denotes that match has been found and there is no need to go further to the next elements in the array. On getting a true return value from the callback function, find() returns the value of that element in the array (an object in this case).

Using Array.findIndex()

Array.findIndex() is similar to Array.find() but it returns the index of the matched element.

If the element does not exist, then -1 is returned.

var obj = [
    {name: 'Max', age: 23},
    {name: 'John', age: 20},
    {name: 'Caley', age: 18}
];

var index = obj.findIndex(e => e.name === 'John');
console.log(index); // 1

if (index !== -1) {
    console.log(obj[index]); // { name: 'John', age: 20 }
}

Using Array.filter()

Another plausible way is to filter the array to return all objects that pass the specified predicate. This can be easily done using the filter() method.

var obj = [
    {name: 'Max', age: 23},
    {name: 'John', age: 20},
    {name: 'Caley', age: 18}
];

var found = obj.filter(e => e.name === 'John');
if (found.length > 0) {
    console.log(found[0]); // { name: 'John', age: 20 }
}