Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
How to isolate duplicates by property from an array of objects

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"
}]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" },
  ]
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!