0

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
2
  • 1
    arr.some(([a, _]) => a === 1) Commented Aug 8, 2021 at 13:55
  • Nothing wrong with using a loop and breaking the loop if condition met. Built in methods are a bit easier to write but won't have greater efficiency Commented Aug 8, 2021 at 14:00

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

The , _ is pointless. You can just use [a]
Yes, that's true, but it better match OPs expectation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.