Radical_Activity
Radical_Activity

Reputation: 2738

Remove or push if an Array of values exists in another array of objects in ES6, Javascript

I have and array of objects with the details of certain food:

let food = [
    {id: 1, name: 'Peas', comments: ''},
    {id: 2, name: 'Oranges', comments: ''},
    {id: 3, name: 'Bananas', comments: ''},
    {id: 4, name: 'Grapefruits', comments: ''},
    {id: 5, name: 'Apples', comments: ''}
];

A second array includes all the selected food IDs that the user can select in a multi-select dropdown:

let selectedFood = [1, 5];

and a third array is where I want to add/remove items based on the selectedFood IDs - right now it should include IDs 1 and 5:

let newFood = [
   {id: 1, name: 'Peas'},
   {id: 5, name: 'Apples'}
]

If we select a new food, let's say, Bananas, then the selectedFood array should look like:

let selectedFood = [1, 5, 3];

... and the newFood array:

let newFood = [
   {id: 1, name: 'Peas'},
   {id: 5, name: 'Apples'},
   {id: 3, name: 'Bananas'}
]

If we want to remove an item, let's say Peas from the selected food it should remove it from both the selectedFood and newFood arrays:

let selectedFood = [5, 3];

let newFood = [
   {id: 5, name: 'Apples'},
   {id: 3, name: 'Bananas'}
]

Is there any quick and easy way of doing this? I know I can do forEach on selectedFood and find/filter on newFood then push/splice based on the result. However is there a simple ES6 way of achieving this?

Update #1:

One thing that I forgot to mention is, I want to keep the current array instead of creating a new one. The reason for that is, I might change/add some other values before removing/adding an item.

Upvotes: 0

Views: 61

Answers (1)

norbitrial
norbitrial

Reputation: 15166

Using .filter() and .includes():

let food = [
    {id: 1, name: 'Peas', comments: ''},
    {id: 2, name: 'Oranges', comments: ''},
    {id: 3, name: 'Bananas', comments: ''},
    {id: 4, name: 'Grapefruits', comments: ''},
    {id: 5, name: 'Apples', comments: ''}
];

let selectedFood = [1, 5, 3];

const result = food.filter(e => selectedFood.includes(e.id));

console.log(result);

If you need only id and name fields then at the end you can use .map().

I hope this helps!

Upvotes: 2

Related Questions