// all items
var arr = [
{id: 'a1', value: 1},
{id: 'a2', value: 2},
{id: 'a3', value: 2},
{id: 'b1', value: 1},
{id: 'a1', value: 2},
{id: 'a2', value: 3}
]
var filtered = []
// We want mantain the duplicated item with highest value
arr.forEach( item => {
const some = arr.find(x => {if (x.id === item.id && x.value > item.value && !duplicated.includes(x)) {return x}})
if (some) {
duplicated.push(some)
} else if (!duplicated.includes(item)) {
duplicated.push(item)
}
})
console.log(filtered)
// [
// {id: 'a1', value: 2},
// {id: 'a2', value: 3},
// {id: 'a3', value: 2},
// {id: 'b1', value: 1}
// ]
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter