I have an array of objects.
const arr = [
{ title: \"sky\", artist: \"Jon\", id: 1 },
{ title: \"rain\", artist: \"Paul\", id: 2 },
{ title: \"sky\", artis
One way to do it, in order to avoid running an exponential loop is to save all values to a new object, and convert that object to a new array.
const combinedObj = arr.reduce((obj, item) => { obj[item.id] = item; return obj; }, {});
const newArray = Object.values(combinedObj)
you can sort the data by id,then each item that has different id
compared with next element and prev element should be added to the result array.
const arr = [
{ title: 'sky', artist: 'Jon', id: 1 },
{ title: 'rain', artist: 'Paul', id: 2 },
{ title: 'sky', artist: 'Jon', id: 1 },
{ title: 'sky', artist: 'Jon', id: 1 },
{ title: 'rain', artist: 'Paul', id: 2 },
{ title: 'test', artist: 'test', id: 3 },
]
arr.sort((a, b) => a.id - b.id)
var res = []
arr.forEach((item, index) => {
if (index < arr.length - 1 && arr[index + 1]) {
if (item.id === arr[index + 1].id) {
return
}
}
if (index > 0 && arr[index - 1]) {
if (item.id === arr[index - 1].id) {
return
}
}
res.push(item)
})
console.log(res)
output
0: {title: "test", artist: "test", id: 3}