Given the array [{fruit1:"apple"},{fruit2:"banana"},{fruit3:"apple"}] how would I remove an element that had a duplicate value. In this example, I would only want to keep one of the key-value pairs that have "apple", removing that element from an array.
1 Answer
You can reduce the array to a Map. For each object, extract the key/value pair with Object.entries(). Unless a Map's key (apple for example) already exists, use the value as the key of a new Map entry, and the original key as the value. Then you can convert it back to an array using Array.from(), and switch the keys and the values:
const data = [{fruit1:"apple"},{fruit2:"banana"},{fruit3:"apple"}];
const result = Array.from(
data.reduce((m, o) => {
const [k, v] = Object.entries(o)[0];
return m.has(v) ? m : m.set(v, k);
}, new Map()),
([k, v]) => ({ [v]: k })
);
console.log(result);
1 Comment
J.Ko
@MarkMeyer It could be that OP is dealing with user input, and is removing duplicates as it's input, so the data will never have more than one duplicate at a time.