How to get all objects with the same value and then add them to resulting array?
I mean I need to find all duplicates by value (which is unknown in advance) and then return array of all unique objects with a key variant
which holds array of duplicate objects or null
if nothing found.
const products = [
{
position: 1,
category: "jeans",
},
{
position: 2,
category: "tees",
},
{
position: 3,
category: "dress",
},
{
position: 4,
category: "dress",
},
{
position: 5,
category: "dress",
},
];
// output
const output = [
{
position: 1,
category: "jeans",
variants: null,
},
{
position: 2,
category: "tees",
variants: null,
},
{
position: 3,
category: "dress",
variants: [
{
position: 3,
category: "dress",
},
{
position: 4,
category: "dress",
},
{
position: 5,
category: "dress",
},
],
},
];
2
Answers
You could use something like the following:
In essence, we’re creating a lookup map which stores all the categories, and then appending any variants to the category already in the map.
As for why, it saves us the effort of having to constantly check for duplicates in the array by utilizing the O(1) lookup time of JS objects.
here you go: