Javascript: filter an array of objects by an array of strings

I wonder if there is a more elegant way to do this. Suppose I have an array of such objects:

a = [
  {
    "id": "kpi02",
    "value": 10
  },
  {
    "id": "kpi02",
    "value": 30
  },
  {
    "id": "kpi02",
    "value": 11
  },
  {
    "id": "kpi02",
    "value": 33
  },
  {
    "id": "kpi03",
    "value": 1
  },
  {
    "id": "kpi03",
    "value": 0.5
  },
  {
    "id": "kpi04",
    "value": 0.5
  }
]

Now I want to filter the property idto return all objects with a match in another array

var kpis = ["kpi03", "kpi02"];

I came up with this solution:

var b = [];
for (j in kpis) {
 for (i in a) { 
    if (a[i].id == kpis[j]) {
    b.push(a[i]);
    }
 }
}

Coming from R, this seems a bit complicated, is there any way to do this with a prototype filter? Like this, but with an array of strings to compare instead of a single string:

 var b = a.filter( function(item){return (item.id == "kpi03");} );

Thank you so much!

+4
source share
2 answers

You can use indexOf in a filter like this

var res = a.filter(function (el) {
  return kpis.indexOf(el.id) >= 0; 
});

Example

+7
source

Just use Array.indexOf

var b = a.filter(function(item){return kpids.indexOf(item.id) > -1 });

Array.indexOf , , indexOf. -1, , .

, , -1

+1

All Articles