'JavaScript: add new property to array elements according to another array
I have two arrays.
When comparing, if arr1 property id matches with arr2 property id, then add new property tag: assign else add tag: ''
I have tried the below code:
var result = arr1.filter(({ id: id }) =>
!arr2.some(({ name: name }) => name === id)
);
Sample inputs:
var arr1 = [
{id:1, name: "ram"},
{id:24, name: "zen"},
{id: 3, name: "sam"}
]
var arr2 = [
{id:24, name: "zen"},
{id: 3, name: "sam"}
]
Expected Output:
[
{id:1, name: "ram", tag:''},
{id:24, name: "zen", tag: 'yes'},
{id: 3, name: "sam", tag: 'yes'}
]
Solution 1:[1]
- Create a
Setof ids inarr2usingArray#map - Again, using
Array#map, iterate overarr1and settagusingSet#has
const
arr1 = [ {id:1, name: "ram"}, {id:24, name: "zen"}, {id: 3, name: "sam"} ],
arr2 = [ {id:24, name: "zen"}, {id: 3, name: "sam"} ];
const arr2IdsSet = new Set( arr2.map(({ id }) => id) );
const res = arr1.map(e => ({ ...e, tag: arr2IdsSet.has(e.id) ? 'yes' : '' }));
console.log(res);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Majed Badawi |
