2

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"}
]
4
  • 2
    Do you want to always remove the previous row or just the existing row that has similar id? Commented Feb 22, 2018 at 8:07
  • is there only one dupe? do you want only the last one if one or more dupes? what have you tried? Commented Feb 22, 2018 at 8:07
  • its not clear from your question by what rules/criteria you want to remove a lookalike array (syntactically they're not duplicate). Commented Feb 22, 2018 at 8:12
  • @GiovanniLobitos and NinaScholz It may have more than one array with same id and i always want to remove the previous row and keep the last row. Commented Feb 22, 2018 at 8:53

2 Answers 2

10

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)

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

2 Comments

@Arman Charan ..how its working ..could u explain a little ??
I used the following doc references: Array.prototype.map(), Map, Map.values() and Destructuring Assignment.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.