1

I have two arrays.

let arr1 = [{id: 1, favorite: false}, {id: 2, favorite: false}, {id: 3, favorite: false}];
let arr2 = [1, 3];

If the id exists in arr2, I want to change the favorite to true (of that particular object)

For example. in the above case, the final arr1 would look like

[{id: 1, favorite: true}, {id: 2, favorite: false}, {id: 3, favorite: true}];

3 Answers 3

4

You can use .map to iterate over arr1 and .includes to check if the item's id is in arr2:

const arr1 = [
  {id: 1, favorite: false}, 
  {id: 2, favorite: false}, 
  {id: 3, favorite: false}
];
const arr2 = [1, 3];

const res = arr1.map(e => 
  ({...e, favorite: arr2.includes(e.id)})
);

console.log(res);

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

2 Comments

Thanks, exactly what I was looking for!
@rohanharikr you are welcome. Please mark the answer as the solution to close the question
2

You can also use some method like:

const newArr = arr1.map(item =>  { return { ...item, favorite: arr2.some(elem => elem === item.id) } })

Comments

1

You can also use forEach and includes.

let arr1 = [{id: 1, favorite: false}, {id: 2, favorite: false}, {id: 3, favorite: false}];
let arr2 = [1, 3];

arr1.forEach(x => x.favorite = arr2.includes(x.id))

console.log(arr1);

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.