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.

3

1 Answer 1

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

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

1 Comment

Thanks for this. I was hoping for something that didn't use JSON.stringify as it seems a little fragile if the sort fails.

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.