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?

Dan
  • 59,490
  • 13
  • 101
  • 110
Jacob Pedersen
  • 347
  • 2
  • 4
  • 12

5 Answers5

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);
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
0

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

_.find(result, {ID: 3})
djechlin
  • 59,258
  • 35
  • 162
  • 290
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);
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);
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");

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114