Home > Blockchain >  How to cut specific item from array and save it in obj in javascript
How to cut specific item from array and save it in obj in javascript

Time:08-16

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']
}

CodePudding user response:

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);

CodePudding user response:

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 }

  • Related