I have object like this where 'id', is unique. I need to remove duplicates from the array of objects in javascript in any version less than ES5. I need to compare based on the id field and remove its duplicates.
Example:
Object = [
{id: id_one, value: value_one, label: ABC},
{id: id_one, value: value_one, label: ABC},
{id: id_three, value: value_three, label: ABX},
{id: id_two, value: value_two, label: ABY},
{id: id_four, value: value_four, label: ABD}
];
Output:
result = [
{id: id_one, value: value_one, label: ABC},
{id: id_three, value: value_three, label: ABX},
{id: id_two, value: value_two, label: ABY},
{id: id_four, value: value_four, label: ABD}
];
I tried logic like this,
function getDistValues(object) {
var distObject = [];
var tempIndex = [];
var length = object.length;
for (var i = 0; i < length; i++) {
tempIndex.push(object[i].id);
if (tempIndex.indexOf(object[i].id) === -1 || i === 0) {
distObject.push(object[i]);
}
}
return distObject;
}
It is only giving the first object. I tried like mapping the ids and comparing it but not worked.
Any help will be useful to me.
tempIndex.push(object[i].id);BEFORE checkingtempIndex.indexOf(object[i].id), obviously it is always found. Also the best you would get from me is a babel transpile to ES3 from an ES2017 solution, because realistically, who writes ES3 these days?!