3

If I have an array like this:

var array = [{ID:1,value:'test1'},
             {ID:3,value:'test3'},
             {ID:2,value:'test2'}]

I want to select an index by the ID.

i.e, I want to somehow select ID:3, and get {ID:3,value:'test3'}.

What is the fastest and most lightweight way to do this?

3
  • What did you try so far? How did it work out? Commented Apr 10, 2014 at 22:56
  • Silly me experimenting with a for loop. Commented Apr 10, 2014 at 23:04
  • possible duplicate of Find object by id in array of javascript objects Commented Apr 10, 2014 at 23:24

5 Answers 5

5

Use array.filter:

var results = array.filter(function(x) { return x.ID == 3 });

It returns an array, so to get the object itself, you'd need [0] (if you're sure the object exists):

var result = array.filter(function(x) { return x.ID == 3 })[0];

Or else some kind of helper function:

function getById(id) {
    var results = array.filter(function(x) { return x.ID == id });
    return (results.length > 0 ? results[0] : null);
}
var result = getById(3);
Sign up to request clarification or add additional context in comments.

Comments

0

With lodash you can use find with pluck-style input:

_.find(result, {ID: 3})

Comments

0

Using filter is not the fastest way because filter will always iterate through the entire array even if element being search for is the first element. This can perform poorly on larger arrays.

If you are looking for fastest way, simply looping through until the element is found might be best option. Something like below.

var findElement = function (array, inputId) {
    for (var i = array.length - 1; i >= 0; i--) {
        if (array[i].ID === inputId) {
            return array[i];
        }
    }
};

findElement(array, 3);

1 Comment

@nachoalvarez, your code would run into errors. You should use [property] instead of .property
0

I would go for something like this:

function arrayObjectIndexOf(myArray, property, searchTerm) {
    for (var i = 0, len = myArray.length; i < len; i++) {
        if (myArray[i].property === searchTerm)
            return myArray[i];
    }
    return -1;
}

In your case you should do:

arrayObjectIndexOf(array, id, 3);

Comments

0
var indexBy = function(array, property) {
  var results = {};
  (array||[]).forEach(function(object) {
    results[object[property]] = object;
  });
  return results
};

which lets you var indexed = indexBy(array, "ID");

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.