I have an array of objects like this:
const result = [
{ ProductName: 'Orange', Origin: 'Italy' },
{ ProductName: 'Orange', Origin: 'Italy' },
{ ProductName: 'Lemon', Origin: 'Spain' },
{ ProductName: 'Avocado', Origin: 'Chile' }
];
// Expected output since there are duplicates:
const output = [{ ProductName: 'Orange', Origin: 'Italy' }]
Like shown above, there might be duplicates in the array (but it's not a must). That's why I'd like to:
- check if there are duplicates in the array
- if yes: create new array with only duplicates (show duplicate only 1x, even if there might be 2 or 3 duplicated in const result)
- if no: leave const result as is
By now, I tried to modify a code, which does the opposite: it finds unique (not duplicated) objects in the result-array. But I just can't get it work. Maybe it's just a wrong approach? Any help is appreciated!
const endresult = result
.map(e => e.ProductName)
.map((e, i, final) => final.indexOf(e) === i && i)
.filter(e => result[e])
.map(e => result[e]);
out = [{ ProductName: 'Orange', Origin: 'Italy' }]
orout = [{ ProductName: 'Orange', Origin: 'Italy' },{ ProductName: 'Lemon', Origin: 'Spain' },{ ProductName: 'Avocado', Origin: 'Chile' }]