I have array objects with keys path and current. How to remove duplicate elements, where key current has the same value.
let arrPath = [{
path: [1, 2],
current: "K"
}, {
path: [0, 3],
current: "I"
}, {
path: [1, 3],
current: "N"
}, {
path: [1, 4],
current: "N"
}, {
path: [0, 2],
current: "G"
}, {
path: [2, 2],
current: "G"
} ];
You can remove duplicate objects (duplicate object in the sense that it contains duplicate current property) by using reduce.
let arrPath = [{ path: [1, 2], current: "K" }, { path: [0, 3], current: "I" }, { path: [1, 3], current: "N" }, { path: [1, 4], current: "N" }, { path: [0, 2], current: "G" }, { path: [2, 2], current: "G" }]
let resultData = arrPath.reduce((elements, obj, index) => {
let existingData = elements.find(element =>
element.current === obj.current
);
if (!existingData) {
elements.push(obj);
}
return elements;
}, []);
console.log(resultData)
You can map each value in the array to an entry using the current values for the keys.
Then use these entries to construct a Map object, effectively eliminating duplicate entries.
You can convert the Map back to an array using Array.from
Array.from(new Map(arrPath.map(o => [o.current, o])).values())