16 August 2024

To filter a list of objects based on a list of IDs in JavaScript, you can use the filter method combined with the includes method. First, you have an array of IDs and another array of objects where each object has an id property. By using the filter method on the array of objects, you can iterate through each object and check if its id is included in the array of IDs. If it is, the object is kept in the new filtered array. This way, you get a new array that contains only the objects with IDs that are present in your list of IDs.

Source code viewer
  1. // Array of IDs
  2. const ids = [1, 3, 5];
  3.  
  4. // Array of objects
  5. const objects = [
  6. { id: 1, name: 'Object 1' },
  7. { id: 2, name: 'Object 2' },
  8. { id: 3, name: 'Object 3' },
  9. { id: 4, name: 'Object 4' },
  10. { id: 5, name: 'Object 5' }
  11. ];
  12.  
  13. // Filtered array of objects based on the array of IDs
  14. const filteredObjects = objects.filter(obj => ids.includes(obj.id));
  15.  
  16. console.log(filteredObjects);
Programming Language: Javascript