UI_Brain
UI_Brain

Reputation: 93

How to replace forEach with map for the below in Javascript

There are two arrays and both have id attributes along with other properties. Requirement is compare two arrays and create new to add age property to corresponding object in arr1

let arr1 = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'
}];

let arr2 = [{
  id: 1,
  age: 20
}, {
  id: 3,
  age: 35
}];
const newArr = [];

arr1.forEach(obj => {
  return arr2.forEach((obj2) => {
    if (obj.id === obj2.id) {
      newArr.push(Object.assign({}, obj, {
        age: obj2.age
      }))
    }
  })
})
 console.log(newArr);
//outputs [{id:1, name: 'a', age:20}, {id:3, name: 'c', age:35}]

Upvotes: 1

Views: 974

Answers (1)

Tranbi
Tranbi

Reputation: 12701

I don't know if it's the most elegant solution but you can create your function and map with it:

let arr1 = [{
    id: 1,
    name: 'a'
  }, {
    id: 2,
    name: 'b'
  }, {
    id: 3,
    name: 'c'
}];
  
let arr2 = [{
    id: 1,
    age: 20
  }, {
    id: 3,
    age: 35
}];

function addAge(elt, arr2) {
    let elt_w_age = arr2.find(x => x.id === elt.id);
    if (elt_w_age != null) {
        elt.age = elt_w_age.age
        return elt
    }
    else {
        return null
    }
}

console.log(arr1.map(x => addAge(x, arr2)).filter(x => x !== null))

Upvotes: 1

Related Questions