0

How can I get the last object from an array of identical objects. I attached the code. I will appreciate any help. Thank you!

Input

[
      {name:'Sam', count:3},
      {name:'Sam', count:5},
      {name:'Sam', count:8},
      {name:'Jill', count:7},
      {name:'Jill', count:6},
    ]

Output

 [
      {name:'Sam', count:8},
      {name:'Jill', count:6},
 ]
3
  • Do you want to get the last record of each item by name? Commented Nov 11, 2022 at 8:45
  • 1
    Duplicate of How to get the last occurrence of the duplicated array in Javascript. Basically const result = Array.from(yourArray.reduce((result, object) => { result.set(object.name, object); return result; }, new Map()).values());. See the documentation. Commented Nov 11, 2022 at 8:49
  • @lucumt yes, each item by name Commented Nov 11, 2022 at 8:50

1 Answer 1

2

You can use reduce() to do it, each time we check if the name exists or not,if it exists then remove the exists one and put the new one into the result array


Update: Based on @Simon's comment,I update my answer with more simple code

let data = [
      {name:'Sam', count:3},
      {name:'Sam', count:5},
      {name:'Sam', count:8},
      {name:'Jill', count:7},
      {name:'Jill', count:6},
    ]
    
let result = Object.values(data.reduce((a,c) => {
   a[c.name] = c
   return a
},{}))    
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.