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

137
Views
How can I delete a item from an array and push a result?

I have this array:

 [
  {
   "id": "z12",
   "val": "lu",
   "val2": "1",
  },
  {
   "id": "z13",
   "val": "la",
   "val2": "2",
  },
  {
   "id": "z14",
   "val": "lo",
   "val2": "3",
  },
]

I have second

    array2 = {
      tab: [],
    }

i do in my typeScript :

   array.forEach((item, index)=>{
    if(item.id === z12){
      array.splice(index, 1);
    }else{
      array2.tab.push(item.id);
    }
});

I should normally have: tab: [z13,z14] but it does not work

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

0

You can filter and map directly.

const array = [{ "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2": "2", }, { "id": "z14", "val": "lo", "val2": "3", },];

const array2 = {
  tab: array.filter(e => e['id'] != "z12").map(e => e['id']),
}

console.log(array2)

about 4 years ago · Juan Pablo Isaza Report

0

I think you could make it in two steps:

// first remove the "z12" from the array as you requested
array = array.filter(e => e.id !== 'z12')

// and second get the remaining ids
array2 = {
  tab: array.map(e => e.id)
}
about 4 years ago · Juan Pablo Isaza Report

0

splice() method in forEach() cause the problem when the "z12" was removed, the array became

 [
  {
   "id": "z13",
   "val": "la",
   "val2": "2",
  },
  {
   "id": "z14",
   "val": "lo",
   "val2": "3",
  },
]

BUT the iteration of forEach method did not stop itself. it will continue with index of 1 that just after the z12 was removed so the index of 1 is the "z14", not the "z13".

some knowledge of forEach forEach is BAD!

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!