1

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 1

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.