find match in array object js

How to Find a Match in Array Object in JavaScript

Array objects are one of the most used data structures in JavaScript. They allow you to store multiple values in a single variable. You might come across a situation where you need to find a specific value or a match in an array object. In this post, we will discuss different ways to find a match in an array object in JavaScript.

Method 1: Using the find() method

The find() method returns the value of the first element in the array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.


const users = [{
  id: 1,
  name: 'John'
}, {
  id: 2,
  name: 'Mary'
}, {
  id: 3,
  name: 'Peter'
}];

const user = users.find(u => u.id === 2);
console.log(user); // Output: {id: 2, name: "Mary"}

Method 2: Using the filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.


const users = [{
  id: 1,
  name: 'John'
}, {
  id: 2,
  name: 'Mary'
}, {
  id: 3,
  name: 'Peter'
}];

const user = users.filter(u => u.id === 2);
console.log(user); // Output: [{id: 2, name: "Mary"}]

Method 3: Using the some() method

The some() method tests whether at least one element in the array passes the test implemented by the provided function.


const users = [{
  id: 1,
  name: 'John'
}, {
  id: 2,
  name: 'Mary'
}, {
  id: 3,
  name: 'Peter'
}];

const isUserFound = users.some(u => u.id === 2);
console.log(isUserFound); // Output: true

Method 4: Using the indexOf() method

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.


const users = [{
  id: 1,
  name: 'John'
}, {
  id: 2,
  name: 'Mary'
}, {
  id: 3,
  name: 'Peter'
}];

const index = users.findIndex(u => u.id === 2);
console.log(index); // Output: 1

In conclusion, there are multiple ways to find a match in an array object in JavaScript. Depending on your use case, you can choose any of the methods discussed above.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe