0

I'm trying to remove duplicates from a nested array of objects.

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},
{
  type: "horizontal",
  tiles: [{ col: 1, row: 3 }, { col: 2, row: 3 }, { col: 0, row: 3 }]
},
{
  type: "horizontal",
  tiles: [{ col: 2, row: 3 }, { col: 1, row: 3 }, { col: 0, row: 3 }],
},
{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

I'm trying to only keep the top level objects if they are unique. As you can see the tiles array isn't necessarily sorted by col/row.

So arr here would become:

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

I've looked extensively but can't quite find something that solves the same problem I'm trying to solve.

kabatwa
  • 69
  • 1
  • 4
  • Does this answer your question? [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – pilchard Feb 12 '22 at 16:20
  • I think you are able to check this url https://stackoverflow.com/questions/67487238/remove-duplicates-from-nested-array-of-objects – Hu Zhi Xing Feb 12 '22 at 16:23
  • Unfortunately not. I've been looking at that question and have been trying to adapt it but my structure has an extra array surrounding it. – kabatwa Feb 12 '22 at 16:23

1 Answers1

0

Okay this may be a little long but I couldn't find a shorter way of doing. My plan was to get a Set of JSON strings (which gives unique) and to convert it back to array of JS objects (Set of JS objects won't remove duplicates). This way will get only the unique values.

But for the JSON strings to be equal for unique records the tiles array has to be in same order so I ran sort on tiles first to make sure the order is same

let arr = [{
  type: "horizontal",
  tiles: [{ col: 0, row: 3 }, { col: 1, row: 3 }, { col: 2, row: 3 }]
},{
  type: "horizontal",
  tiles: [{ col: 1, row: 3 }, { col: 2, row: 3 }, { col: 0, row: 3 }]
},{
  type: "horizontal",
  tiles: [{ col: 2, row: 3 }, { col: 1, row: 3 }, { col: 0, row: 3 }],
},{
  type: "vertical",
  tiles: [{ col: 0, row: 5 }, { col: 0, row: 3 }, { col: 0, row: 4 }],
}];

//sort for ascending order of col field
arr.forEach((o,i,a) => {
    a[i].tiles.sort((a,b) => a.col-b.col)
})


let mySet = new Set();
arr.forEach(item => mySet.add(JSON.stringify(item)))

let result = []
mySet.forEach((el) => {
    result.push(JSON.parse(el))
})


console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
cmgchess
  • 7,996
  • 37
  • 44
  • 62
  • Thanks for this. I was hoping for something that didn't use `JSON.stringify` as it seems a little fragile if the sort fails. – kabatwa Feb 12 '22 at 21:50