16

I wonder if there is a more elegant way of doing this. Suppose i have an array of objects like this:

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 on the id property, to 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 that with the filter prototype? Like this but with an array of strings to compare with instead of a single string:

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

Thanks a lot!

4 Answers 4

22

You can use indexOf in filter, like this

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

Example

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick answer and the example! I knew there must be a more elegant solution :)
14

Another nice alternative is using .filter with .includes:

var result = a.filter(item => kpis.includes(item.id))

Comments

3

If you want them in the order of the array of string then

    var result = [];
kpis.map((item) => {
    const matchedObject = a.find(
        (option) => option.id === item
    );
    result.push(matchedObject);
});

Comments

2

Just make use of Array.indexOf

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

Array.indexOf returns the index of the argument passed in the array on which indexOf is being called on. It returns -1 if there isn't the element which we are looking for.

So, we make sure that it index is greater than -1

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.