0

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.

1 Answer 1

2

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!

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

2 Comments

The important part is that functions like filter and map always create new arrays. So there is no need to modify existing arrays.
Thank you. This is actually a pretty good approach and almost good for me. One thing that I forgot to mention is ideally 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. I've updated the original question with this.

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.