1

From this array of objects, I'd like to get multiple arrays containing the objects that have the same values for the "id" property:

var obj1 = { id: 1, name: "apple"};
var obj2 = { id: 2, name: "pear"};
var obj3 = { id: 3, name: "melon"};
var obj4 = { id: 4, name: "cherry"};
var obj5 = { id: 2, name: "banana"};
var obj6 = { id: 1, name: "pinapple"};
var obj7 = { id: 1, name: "peach"};
var array = [obj1, obj2, obj3, obj4, obj5, obj6, obj7];

Example of the arrays I'd like to retrieve:

[{
  id: 1,
  name: "apple"
}, {
  id: 1,
  name: "pinapple"
}, {
  id: 1,
  name: "peach"
}]

[{
  id: 2,
  name: "pear"
}, {
  id: 2,
  name: "banana"
}]
1

1 Answer 1

3

There's a groupBy utility function in a library like lodash that you can use, otherwise you'd have to write your own version of that. It would look something like

function myGroupById (array) {
    const group = {};

    array.forEach(elem => {
        group[elem.id] = group[elem.id] || [];
        group[elem.id].push(elem)
    })

    return group;
}

function extractDuplicatesOnly(array) {
    for (const obj in array) {
        if (array[obj].length < 2) {
            delete array[obj]; 
        }
    }
    return array;
}
myArray = myGroupById(myArray);
myArray = extractDuplicatesOnly(myArray);
console.log(myArray);

applying that to your data will yield an object that looks like this:

{
  1: [
    { id: 1, name: "apple" },
    { id: 1, name: "pinapple" },
    { id: 1, name: "peach" },
  ],
  2: [
    { id: 2, name: "pear" },
    { id: 2, name: "banana" },
  ]
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Joshua. I made some edits to your answer to match my question.

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.