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

160
Views
Update an element from one of multiple arrays

I have an object of 4 arrays like following

const data = {
  arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
  arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
  arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
  arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}

Then I need to find an element and update it. Here is what I tried:

const updateElement = (id: number, newName: string) => {
  let idx: number;

  idx = data.arr1.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr1[idx].name = newName;

  idx = data.arr2.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr2[idx].name = newName;

  idx = data.arr3.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr3[idx].name = newName;

  idx = data.arr4.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr4[idx].name = newName;
}

Is there any better way to update an element form multiple arrays than my approach? Suppose that every array has the same element interface.

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

0

you can use Object.values() and flat() array for update it :

const data = {
  arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
  arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
  arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
  arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}
const updateElement = (id, newName) => {
  const values = Object.values(data).flat().find(ele => ele.id === id)
  if(values) values.name = newName
}
updateElement(1, 'newName')
console.log(data)

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!