1

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?

1
  • For any such collections / arrays functions, use the beautiful and elegant underscore.js (underscorejs.org). I am sure you can find the functions you need in this library. Commented Apr 1, 2015 at 18:52

6 Answers 6

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

int is no javascript?
Good catch. Been coding in c# and vba all day. Edited.
Yes, even if I know he surely doesn't have the same account twice.
0

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/

1 Comment

Yours has the same problem mine did. If the term you're searching for is in the array twice, it returns the index of it's last instance. jsfiddle.net/eguj3d5e/1
0

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();

Comments

0

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');

2 Comments

Your find function doesn't return anything.
true wrote it too fast
-3
index = indexOf(arr, 'Account 2')

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.