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

164
Views
Replace elements of array

I have two arrays as follows:

array1 = [
 {
  "id":"1",
   "name":"George",
   "City":"california"
 },
 {
  "id":"2",
   "name":"James",
   "City":"Paris"
 },
  {
  "id":"3",
  "name":"Julie",
  "City":"rome"
 }
]

array2 = [
 {
  "id":"2",
   "name":"jonty",
   "City":"wales"
 },
 {
  "id":"5",
   "name":"kite",
   "City":"mumbai"
 },
  {
  "id":"3",
  "name":"neha",
  "City":"pune"
 }
]

I want to check if any element with particular id in array2 exist in array1. If element with that id exist, then replace that element in array1 else push that element in array1. Final array will look as follows:

finalArray = [
{
  "id":"1",
   "name":"George",
   "City":"california"
 },
 {
  "id":"2",
   "name":"jonty",
   "City":"wales"
 },
  {
  "id":"3",
  "name":"neha",
  "City":"pune"
 },
 {
  "id":"5",
   "name":"kite",
   "City":"mumbai"
 }
]

How can I do that?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

This creates a duplicate of array one. It then loops over every item in array 2 and inserts it into the output array if it has a unique id. If it has the same id, then it replaces the item from array1 to array2.

const outArray = [...array1];

for (const item of array2)
{
    const { id } = item;
  
    const existingIndex = outArray.findIndex(element => element.id === id);

    if(existingIndex != -1) {
        outArray[existingIndex] = item;
    }
    else {
        outArray.push(item);
    }
}

// outArray is the output

about 4 years ago · Santiago Trujillo 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!