Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS / Javascript How to remove the duplicate array from multi dimentional array?

I have a multi dimentional array as following. I need to delete the previous row if the value of the particular key value duplicates

[
  {"id":5, "name":"abc"}
  {"id":5, "name":"abcd"}
  {"id":6, "name":"abcde"}
]

I need to get the result as following after deleting the previous row if the value of id already exists.

[
  {"id":5, "name":"abcd"}
  {"id":6, "name":"abcde"}
]
like image 305
Hareesh Avatar asked May 23 '26 10:05

Hareesh


1 Answers

Map can be leveraged to produce a pretty cool one-liner 😁

const input = [
  {"id":5, "name":"abc"},
  {"id":5, "name":"abcd"},
  {"id":6, "name":"abcde"}
]

const output = [...new Map(input.map(o => [o.id, o])).values()]

console.log(output)
like image 51
Arman Charan Avatar answered May 24 '26 22:05

Arman Charan