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.
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)
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; }
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
{ id: 1, name: [“James”, “Jake”] }
?