How to find if the element with a specific id exists or not with JavaScript?

Estimated read time 1 min read

If you have an array of objects, you can use the Array.prototype.find() method to check if an object with a specific id exists in the array. Here’s an example:

let arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'cherry'}];
let searchId = 2;

let result = arr.find(obj => obj.id === searchId);

if (result) {
  console.log(`An object with id "${searchId}" exists in the array`);
} else {
  console.log(`An object with id "${searchId}" does not exist in the array`);
}

This will output An object with id "2" exists in the array.

If you’re using Lodash, you can use the _.find() method, which works in a similar way:

let arr = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 'cherry'}];
let searchId = 2;

let result = _.find(arr, ['id', searchId]);

if (result) {
  console.log(`An object with id "${searchId}" exists in the array`);
} else {
  console.log(`An object with id "${searchId}" does not exist in the array`);
}

This will also output An object with id "2" exists in the array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply