0

I have an array of objects in my Javascript/React app:

[
 {type: 'TypeOne'} 
 {type: 'TypeFive'}
 {type: 'TypeTen'}
]

How to return a boolean true if the array contains an object with key/value type: 'TypeTen'?

meez
  • 3,783
  • 5
  • 37
  • 91
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some -> `array.some(f => f.type === 'TypeTen')` – Keith Jun 07 '23 at 13:56

2 Answers2

0

You can use the Array.prototype.some() method along with an arrow function. Here's an example:

function checkTypeExists(targetType) {
    return arr.some(obj => obj.type === targetType);
}
vedran77
  • 67
  • 4
0

So there are two ways to do this:

  1. The trivial way (using the syntactical features of JavaScript)
  2. The better way (using Array methods to solve your issue)

1. The Trivial Way

This way can be clearer and allow beginners to read your code easily. It's also cleaner and slightly more efficient:

const source = [ { 'type': 'TypeOne' }, ... ]
for (const obj of source)
    if (obj.type == 'TypeTen')
        return true
return false

2. The better way

This way is better (in my opinion) because of brevity. It's a one-liner and still easy enough to read and understand. It will be slightly less efficient in larger arrays since it has to invoke a callback arr.length times.

arr.some(obj => obj.type == 'TypeTen')
Viraj Shah
  • 754
  • 5
  • 19