6

I have an array of tuples, where first element of tuple is string and second is int. Every tuple has array structure:

var array = [["ele1",1], ["ele2",1], ["ele3",1], ["ele4",1]];

How can I easily check if a string is element of a tuple in array of tuples in javascript?

if array.contains(tuple with first element "ele2")

Is it possible to do it without for loop (checking each element of array)?

3 Answers 3

8

If you are using a relatively modern browser you can just do this:

array.some(function(a) {
    return a[0] === 'string that you want';
})

or, more compactly:

array.some(a => a[0] === 'string that you want')

see Array.some

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

Comments

1

Might seem like a hack but still... :)

array.toString().split(',').indexOf('ele2') % 2 == 0

Comments

0

There isn't an 'easy way'. You will have to iterate through the array and do a check on every element:

var i = array.length, foo;
while (i--) {
   foo = array[i];
   if (foo[0] == 'ele2') {
       break; //success!
   }
}

Or the functional equivalent in the other answer.

Comments

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.