Skip to content Skip to sidebar Skip to footer

Compare Array Of Objects To Array Of Ids

Using jQuery, I would like to use an array of ids to find the objects inside the allObjects array that have the matching Id value. var arrayOfIds = [1, 4, 5]; var allObjects = [{'

Solution 1:

You don't need jQuery for this. You can use Array.prototype.filter() to filter allObjects and Array.prototype.includes() to check if the objects Id property is in arrayOfIds:

allObjects.filter(x=> arrayOfIds.includes(Number(x.Id)))

See demo on JS Bin.

Solution 2:

Best is you transform the array to an object itself:

functionatoo(a)
{
  var i, obj;

  obj = {};

  for (i = 0; i < a.length; i++)
  {
    obj[a[i].Id] = a[i];
  }

  return obj;
}

You can now access all items in the array through the object by simply addressing them as an index:

obj["4"]

returns the correct object that is also stored in the array under a[3].

There is no jQuery involved which should be considered a feature because it is a general solution to all kinds of these problems.

Using a filter (as in Array.prototype.filter()) is easier to write but also incurs in performance problems when you access the items very often or the array is very large. The above solution relies on the internal implementation of the object referencing which is as fast as you can wish for.

Solution 3:

You can use filter() method like following.

var arrayOfIds = [1, 4, 5];
var allObjects = [{ "Id": "1", "name": "aa" }, { "Id": "2", "name": "bb" }, { "Id": "3", "name": "cc" }, { "Id": "4", "name": "dd" }, { "Id": "5", "name": "ee" }, { "Id": "6", "name": "ff" }, { "Id": "7", "name": "gg" }, { "Id": "8", "name": "hh" }, { "Id": "9", "name": "ii" }];
var result = $(allObjects).filter(function() { return arrayOfIds.indexOf(+this.Id) > -1 }).get();

Post a Comment for "Compare Array Of Objects To Array Of Ids"