0

For an array of objects ["a","b","a","c","d","b"] I'd like to get an array of the duplicates: ["a","b"].

Is there a way to do this efficiently, similar to set ([...new Set(myArray)];)?

1
  • 5
    please add your try. Commented Jun 17, 2021 at 17:44

1 Answer 1

1

You could still use a Set and filter the array by checking the existence.

const
    items = ["a", "b", "a", "c", "d", "b"],
    duplicates = items.filter((s => v => s.has(v) || !s.add(v))(new Set));

console.log(duplicates);

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

2 Comments

Won't work if there are more than 2 occurrences. ["a", "a", "a"] returns ["a", "a"]
@adiga, it just filters the first occurences.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.