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

122
Views
How to cut specific item from array and save it in obj in javascript

I have an array which i want to change that array item as an object as shown below.

let a=['monkey: animal','John:human', 'Rob:human', 'donkey:animal']

I need output as below;

output={
    animal: ['monkey', 'donkey'],
    human: ['John', 'Rob']
}
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Here's one solution using String#split and Array#reduce:

let a = ['monkey: animal','John:human', 'Rob:human', 'donkey:animal'];

const output = a
  .map(text => text.split(':').map(t => t.trim()))
  .reduce((acc, [name, specie]) => {
    if (acc[specie]) {
      acc[specie].push(name);
    } else {
      acc[specie] = [name];
    }
    return acc;
  }, {});

console.log(output);

about 4 years ago · Santiago Trujillo Report

0

The ordinary approach to data aggregation:

const arr = ['monkey: animal','John:human', 'Rob:human', 'donkey:animal'];

const result = arr.reduce((acc, item) => {
    const [value, key] = item.split(':').map(e => e.trim());
    acc[key] ??= [];
    acc[key].push(value)
    return acc;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

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!