I have the following data structure that i receive from the api:
[
{
cat_id: '10000844',
cat_id_full: '10000844-01',
order: '20',
},
{
cat_id: '10000844',
cat_id_full: '10000844-02',
order: '50',
},
{
cat_id: '50000844',
cat_id_full: '50000844-52',
order: '10',
},
{
cat_id: '80000844',
cat_id_full: '80000844-32',
order: '51',
},
{
cat_id: '80000844',
cat_id_full: '80000844-12',
order: '12',
},
]
The perfect outcome of cleaning the code would be this result, basically returning only the non-duplicated array sorted by the order:
[
{
cat_id: '10000844',
cat_id_full: '10000844-01',
order: '20',
},
{
cat_id: '50000844',
cat_id_full: '50000844-52',
order: '10',
},
{
cat_id: '80000844',
cat_id_full: '80000844-12',
order: '12',
},
]
But currently it only returns the first found duplicate in a unique array, with the current code (using lodash uniqBy, but it does not have to be one using lodash):
const uniqueCats = uniqBy(cats, 'cat_id');
CodePudding user response:
How about a quick reduce:
Object.values(a.reduce((acc, current) => {
if(!acc[current.cat_id]) {
acc[current.cat_id] = current
} else {
if (acc[current.cat_id].order > current.order) {
acc[current.cat_id] = current
}
}
return acc},
{}))
CodePudding user response:
Try this
function removeDublicats(arr = [], proprety = "") {
const set = new Set();
const result = [];
for (let i = 0; i < arr.length; i ) {
const item = arr[i];
if (set.has(item[proprety])) continue;
set.add(item[proprety]);
result.push(item);
}
return result;
}
CodePudding user response:
You can use Array.prototype.reduce() and extract array result with Object.values()
Code:
const cats = [{cat_id: '10000844',cat_id_full: '10000844-01',order: '20',},{cat_id: '10000844',cat_id_full: '10000844-02',order: '50',},{cat_id: '50000844',cat_id_full: '50000844-52',order: '10',},{cat_id: '80000844',cat_id_full: '80000844-32',order: '51',},{cat_id: '80000844',cat_id_full: '80000844-12',order: '12',},]
const uniqBy = (arr, key) => Object.values(
arr.reduce((a, c) => {
a[c[key]] = a[c[key]]?.order < c.order
? a[c[key]]
: c
return a
}, {}))
const uniqueCats = uniqBy(cats, 'cat_id')
console.log(uniqueCats)