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

67
Views
Get last elements of array having same ID

Get the last values from the array having same ids:

Input:

[{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}]

Required Output:

[{id:1,name:"C++"},{id:2,name:"Php"}]

So, I have tried doing

array?.reverse().filter( (ele, ind) => ind === array.findIndex((elem) => elem?.id === ele?.id))

but it gives me the output [{id:1,name:"Java"},{id:2,name:"C"}]

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

0

You can use a straightforward Array.reduce() for this purpose, creating a map keyed on id. We'll use Object.values() to turn our map into an array:

const input = [{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}];

const result = Object.values(input.reduce((acc, cur) => { 
    acc[cur.id] = cur;
    return acc;
}, {}))

console.log('Result:', result)

One could also use a Map and reduce again:

const input = [{id:1,name:"Java"},{id:1,name:"JavaScript"},{id:1,name:"Python"},{id:1,name:"C++"},{id:2,name:"C"},{id:2,name:"Ruby"},{id:2,name:"Php"}];
const result = [...input.reduce((acc, cur) => {
    return acc.set(cur.id, cur);
}, new Map()).values()];
console.log('Result:', result);

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!