Joshua Gilman
Joshua Gilman

Reputation: 1202

Searching for first index in an array of arrays with Javascript

I have data as such:

[['Account 1', 122.00], ['Account 2', 342.33], ['Account 3', 103.32]]

I wish to be able to check to see if a string exists in any of the first indexes of the arrays and find it's index in the overall array. In other words:

index = find(arr, 'Account 2') // This would return 1

Does JS already have something internal that can do this?

Upvotes: 1

Views: 92

Answers (6)

Thegree0ne
Thegree0ne

Reputation: 185

Works like this...

var arr = [['Account 1', 122.00], ['Account 2', 342.33], ['Account 3', 103.32]];

var find = function(array, string) {
    var ret;
    array.forEach(function(arr, index) {
        if(arr[0] === string){
            ret = index;
        }
    });
    return ret;
}

find(arr, 'Account 2');

Upvotes: 0

NYTom
NYTom

Reputation: 524

Here is how to do it using open source project jinqJs

See Fiddle Example

var myarr = [['Account 1', 122.00], ['Account 2', 342.33], ['Account 3', 103.32]];
var result = jinqJs().from(myarr).where(function(row){return row[0] === 'Account 2'}).select();

Upvotes: 0

NiloCK
NiloCK

Reputation: 621

This might suit your needs:

var arr = [['Account 1', 122.00], ['Account 2', 342.33], ['Account 3', 103.32]];

function find( data, term ){
    ret = null;
    data.forEach(function(item, index){
        if (item[0] === term)
            ret = index;
    });
    return ret;
};

fiddle: http://jsfiddle.net/eguj3d5e/

Upvotes: 0

9Deuce
9Deuce

Reputation: 676

Not sure if there's something built in, but you could always run a simple loop

var index;
for(var i = 0; i < yourArray.length; i++)
    if(yourArray[i][0] == 'Account 2')
    {
        index = i;
        break;
    }

This will make the index variable the index that you're looking for. You can make this a function in your own code to avoid repeating code.

Upvotes: 1

Bergi
Bergi

Reputation: 665574

In ES6 there will be a findIndex method which will do just what you want here. You'll probably need to shim it, though.

var arr = [['Account 1', 122.00], ['Account 2', 342.33], ['Account 3', 103.32]]
var index = arr.findIndex(function(item) { return item[0] == 'Account 2'; }) // 1

Upvotes: 4

user1789573
user1789573

Reputation: 535

index = indexOf(arr, 'Account 2')

Upvotes: -3

Related Questions