Categories
JavaScript Answers

How to filter an array of objects by array of IDs with JavaScript?

Spread the love

Sometimes, we want to filter an array of objects by array of IDs with JavaScript.

In this article, we’ll look at how to filter an array of objects by array of IDs with JavaScript.

How to filter an array of objects by array of IDs with JavaScript?

To filter an array of objects by array of IDs with JavaScript, we can use the JavaScript array’s filter method.

For instance, we write:

const activeIds = [202, 204]
const serviceList = [{
    "id": 201,
    "title": "a"
  },
  {
    "id": 202,
    "title": "a"
  },
  {
    "id": 203,
    "title": "c"
  },
  {
    "id": 204,
    "title": "d"
  },
  {
    "id": 205,
    "title": "e"
  }
];

const activeServiceList = serviceList.filter((item) => {
  return activeIds.includes(item.id);
});
console.log(activeServiceList);

to call serviceList.filter with a callback that returns the activeIds.includes(item.id).

We call activeIds.includes to check if item.id is in the activeIds array.

This will return the serviceList entries with the id value that is includes in the activeIds array.

Therefore, we get:

[
  {
    "id": 202,
    "title": "a"
  },
  {
    "id": 204,
    "title": "d"
  }
]

logged.

How to filter an array of objects by array of IDs with JavaScript?

To filter an array of objects by array of IDs with JavaScript, we can use the JavaScript array’s filter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *