DEV Community

Avnish
Avnish

Posted on

How to determine if a JavaScript array contains an object with an attribute that equals a given value

You can determine if a JavaScript array contains an object with a specific attribute value by using the Array.prototype.some() method along with a callback function. Here's how you can do it:

// Example 1
const array1 = [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' }];
const value1 = 2;

const result1 = array1.some(item => item.id === value1);
console.log(result1); // Output: true

// Example 2
const array2 = [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' }];
const value2 = 4;

const result2 = array2.some(item => item.id === value2);
console.log(result2); // Output: false

// Example 3
const array3 = [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' }];
const value3 = 'Alice';

const result3 = array3.some(item => item.name === value3);
console.log(result3); // Output: true

// Example 4
const array4 = [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' }];
const value4 = 'Charlie';

const result4 = array4.some(item => item.name === value4);
console.log(result4); // Output: false

// Example 5
const array5 = [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' }];
const value5 = '';

const result5 = array5.some(item => item.name === value5);
console.log(result5); // Output: false
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Example 1: We have an array of objects array1 and a value value1. We use the some() method to iterate through each object in the array and check if any object's id attribute equals value1. Since there is an object with id equal to 2, the result is true.

  2. Example 2: Similar to Example 1, but this time the value2 does not exist in any object's id attribute, hence the result is false.

  3. Example 3: Here, we're checking if any object's name attribute equals value3. Since there is an object with name equal to 'Alice', the result is true.

  4. Example 4: Similar to Example 3, but value4 does not match any name attribute, so the result is false.

  5. Example 5: This example checks if any object's name attribute equals an empty string ''. Since no object's name is an empty string, the result is false.

Top comments (0)