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

141
Views
Group common items together in js

I need to group together all the pId together which has same cId entries. I have the following data -

const data = [{pId:"a", cId: [1,2]}, {pId:"b", cId: [1,2]}, {pId:"c", cId: [3]}];
const data1 = [{pId:"a", cId: [1,2,3]}, {pId:"b", cId: [1,2]}, {pId:"c", cId: [3]}];
const data2 = [{pId:"a", cId: [1,2,3]}, {pId:"b", cId: [1,2,3]}, {pId:"c", cId: [3]}];

Expected output -

data = [{pId:["a","b"], cId: [1,2]}, {pId:["c"],cId: [3]}]
data1 = [{pId:["a","b"], cId: [1,2]}, {pId:["a","c"],cId: [3]}]
data2 = [{pId:["a","b"], cId: [1,2,3]},{pId:["a","b","c"],cId: [3]}]

Please help, in the approach. Kindoff stuck, not able to think which qualifies all the cases

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

From what I can gather you’re looking to group based on array similarity in cId. I think you’re looking at something like this:

function unique (array) {
  return Array.from(new Set(array));
}

function match (cIds) {
  return function (x) {
    return x.cId.join() == cIds;
  }
}

function regroup () {
  return unique(data.map(x => x.cId.join())
    .map(cIds => ({
      pId: data.filter(match(cIds)).map(x => x.pId),
      cId: data.find(match(cIds)).cId
    }));
}

data = regroup(data);
data1 = regroup(data1);
data2 = regroup(data2);

Please note that this is a very naive way of comparing arrays by values (there’s a lot of joins involved). This is not production-code ready, but you get the drift of how to handle this problem.

about 4 years ago · Santiago Trujillo 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!