Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check if first element of tuple exists in array of tuples

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)?

like image 856
Matt Avatar asked Oct 31 '14 11:10

Matt


2 Answers

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

like image 102
codebox Avatar answered Nov 15 '22 04:11

codebox


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

array.toString().split(',').indexOf('ele2') % 2 == 0
like image 36
Nikhil Baliga Avatar answered Nov 15 '22 03:11

Nikhil Baliga