Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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}]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!