0

If I have an array like this one:

var arr = [
    { id: 1 , name: "James"},
    { id: 2, name: "John"},
    { id: 1, name: "Jake"}
]

How can I group by a property, like this:

{ id: 1, name: "James", "Jake" },
{ id: 2, name: "John"}

etc.

3
  • Invalid output! You meant an array of names? Commented May 1, 2018 at 1:11
  • Do you perhaps mean { id: 1, name: [“James”, “Jake”] }? Commented May 1, 2018 at 1:12
  • @kshetline - Yes, exactly. Commented May 1, 2018 at 3:57

3 Answers 3

3

Normally when you are trying to group by a single value, you add things to a hash of some sort — that can be an javascript object or Map. Because the keys of these data types need to be unique it makes it easy to pull things together.

For example this uses an object to pull all the ids under one key. Then uses Object.values() to get back and array:

var arr = [{ id: 1 , name: "James"},{ id: 2, name: "John"},{ id: 1, name: "Jake"}]
let hash = arr.reduce((a,c) => {
    // a is an object passed into reduce
    // if it already has a key for c.id just push into the name array
    if (a[c.id]) a[c.id]['name'].push(c.name)
    // if not, add a key for c.id and set it to an object
    // with and id and name array
    else a[c.id] = {id: c.id, name:[c.name]}
    return a
    }, {}) // <-- this {} becomes 'a' (for accumulator) in the reduce loop

// now if you want an array, just take the values
newObj = Object.values(hash)
console.log(hash)
console.log(newObj)

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

Comments

2

Assuming you want an array of names, you can use the function reduce to group the names by id.

const arr = [    { id: 1 , name: "James"},    { id: 2, name: "John"},    { id: 1, name: "Jake"}],
      result = Object.values(arr.reduce((a, {id, name}) => {
        (a[id] || (a[id] = {id, name: []})).name.push(name);
        return a;
      }, {}));
      
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

2 Comments

Why do IDs need to be greater than zero?
@Mark_M my bad! I forgot the key/name conversion to string from an integer.
0

You can use lodash groupBy method to acomplish this task. Please take a look to _.groupBy documentation at https://lodash.com/docs/4.17.10#groupBy

And remember you do need to fully install lodash, you are able to install only the methods you need https://lodash.com/custom-builds

1 Comment

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.