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

126
Views
how do you turn this into this?

I have an array:

const arr = [
   { name: "Jeff", id: 1 },
   { name: "Mary", id: 2 },
   { name: "Jeff", id: 3 },
   { name: "Mary", id: 4 },
   { name: "Emile", id: 5 },
];

I want to turn it into this:

const obj = {
    Jeff: [1, 3],
    Mary: [2, 4],
    Emile: [5],
};

I tried using the Array.reduce method, but I can't seem to wrap my head around the logic.

const obj = arr.reduce((acc, info) => {
    acc[info[name]] = .... 
    return acc;
}, {});

I assume it can be done with the reduce method

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You are on the right track, you just need to check to see if the array is there.

const arr = [
   { name: "Jeff", id: 1 },
   { name: "Mary", id: 2 },
   { name: "Jeff", id: 3 },
   { name: "Mary", id: 4 },
   { name: "Emile", id: 5 },
];

const result = arr.reduce((acc, { name, id }) => {
  acc[name] = acc[name] || [];  // or if(!acc[name]) acc[name] = [];
  acc[name].push(id);
  return acc;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You can do like this:

const arr = [
  { name: "Jeff", id: 1 },
  { name: "Mary", id: 2 },
  { name: "Jeff", id: 3 },
  { name: "Mary", id: 4 },
  { name: "Emile", id: 5 },
];

const result = arr.reduce(
  (acc, cur) => ((acc[cur.name] || (acc[cur.name] = [])).push(cur.id), acc),
  {}
);

console.log(result);

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!