Search code examples
javascriptarraysreactjspayload

How to return a boolean if array index values are equal to a x & y values


Is there a way to check if array this.state.allBooks contains both id:552 and name:'book2' in the same index and return either true or false... I want to avoid using a for loop if possible.

// Array this.state.allBooks 
O:{id:133, name:'book1'}
1:{id:552, name:'book2'}
2:{id:264, name:'book3'}

previously I've done something similar to the below code, but since array this.state.allBooks has an id and a name I'm not sure what approach to take.

let boolValue = this.state.allBooks.includes(/* check if it includes a single value*/)

//Desired output 
// 1.0) Does this.state.allBooks include both id:552 and name:'book2' in the same index ? 
// a)   if yes return true ... should be yes since both id:552 and name:'book2' are part of the same index '1'
// b)   if no return false

Solution

  • I think you can just use JavaScript's method some of the array class. Some will return true if any of the elements in the array match the given predicate so the following code should do the trick:

    let boolValue = this.state.allBooks.some(bookObject => bookObject.id === 552 && bookObject.name === 'book2');