Hareesh
Hareesh

Reputation: 1587

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"}
]

Upvotes: 2

Views: 5182

Answers (2)

Arman Charan
Arman Charan

Reputation: 5797

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)

Upvotes: 10

Hassan Imam
Hassan Imam

Reputation: 22524

You can use array#reduce and group your data based on id key. In case of duplicate replace the existing one. Then extract out all the values using Object.values().

var data = [{ "id": 5, "name": "abc" }, { "id": 5, "name": "abcd" }, { "id": 6, "name": "abcde" }],
    result = Object.values(data.reduce((r,o) => {
      r[o.id] = o;
      return r;
    },{}));
console.log(result);

Upvotes: 1

Related Questions