Igor Telles
Igor Telles

Reputation: 5

Javascript checking only the first item of an array

I have an array of arrays, i.e. [ [1,2], [1,3] ] and I want to check if is there any 1 as the first element of a subarray. It doesn't matter if it is a [1,2] or [1,3]. I'm interested only in the 1's existence. Sure I could use some loops to do this, but I wonder if is there an elegant "built-in" way to do this in js, something like:

arr.includes([1, _]) // returns true if is there any 1 as first element of an array

Upvotes: 0

Views: 110

Answers (1)

ulou
ulou

Reputation: 5863

some is something you are looking for.

Code example:

const data = [[1, 3], [1, 5]] 

const res = data.some( ([a, _]) => a === 1 ) // less elegant alternative:
                                             // .some(e => e[0] === 1)

console.log(res)

Upvotes: 2

Related Questions