1

I've seen a lot of examples that show how to filter/remove duplicate values from array, but I want to get the duplicates and use them in a new array. So for

array = [
    { id: '1', description: 'foo'},
    { id: '2', description: 'bar'},
    { id: '3', description: 'bloop'},
    { id: '1', description: 'bleep'}
]

I want a new array returned that only contains items with matching Id's like so

[
  { id: '1', description: 'foo'},
  { id: '1', description: 'bleep'}
]

I feel like this should be easier than I'm making it

Edit: The suggestions do not do what I'm asking for. They are either creating lookup tables or removing the items from the original array.

4
  • 1
    Checked this? - stackoverflow.com/questions/53212020/… Commented Jan 27, 2021 at 19:27
  • Id equation is enough for you? Commented Jan 27, 2021 at 19:27
  • Neither of these solutions do what I am asking Commented Jan 27, 2021 at 19:32
  • @ChristopherMellor you claim that your question is substantially different from the suggested duplicate. (i.e. the accepted answer just creates a "lookup table.") However, the answer you have accepted here is functionally identical to the answer accepted over there. Commented Jan 27, 2021 at 23:41

1 Answer 1

1

array = [
    { id: '1', description: 'foo'},
    { id: '2', description: 'bar'},
    { id: '3', description: 'bloop'},
    { id: '1', description: 'bleep'}
]

const duplicates = array.reduce((a, e) => {
  a[e.id] = ++a[e.id] || 0;
  return a;
}, {});

console.log(array.filter(e => duplicates[e.id]));

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.