0

Having this array

[ { name: 'foo', gender: 'm' }, { name: 'bar', gender: 'f' }, { name: 'baz', gender: 'f' }  ]

How is it (maybe in a one-liner) possible to transform it into:

[ { gender: 'f', names: [ { name: 'bar' }, { name: 'baz' } ] } ]

Filtered by gender Vanilla JS, ES6 and/or ES7.

2
  • Hi! Please take the tour and read through the help center, in particular How do I ask a good question? Do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! Commented May 23, 2018 at 7:36
  • (FWIW, map wouldn't really apply here. filter would in some solutions, not in others.) Commented May 23, 2018 at 7:37

2 Answers 2

2

You could filter by gender and map objects with name.

var array = [{ name: 'foo', gender: 'm' }, { name: 'bar', gender: 'f' }, { name: 'baz', gender: 'f' }],
    object = { gender: 'f', names: array
        .filter(({ gender }) => gender === 'f')
        .map(({ name }) => ({ name }))
    };

console.log(object);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use array#reduce to group your data based on gender in an object accumulator. Then get all the values from this object using Object.values().

const data = [ { name: 'foo', gender: 'm' }, { name: 'bar', gender: 'f' }, { name: 'baz', gender: 'f' }  ],
      group = Object.values(data.reduce((r, {name, gender}) => {
        r[gender] = r[gender] || {gender, names : []};
        r[gender].names.push({name});
        return r;
      },{}));
console.log(group);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.