How to group object array by a certain key in JavaScript?
There are 2 ways for that.
This article explains the ways with sample codes.
Example objects to be grouped by
For example, suppose we have such an array of objects.
Sample object arrays :
const logins = [ {userId:1, device:'Windows'}, {userId:3, device:'Mac'}, {userId:6, device:'Windows'}, {userId:2, device:'Linux'}, {userId:4, device:'Mac'}, {userId:5, device:'Windows'} ];
Group by this objects with the ‘device’ key like this :
{ "Windows":[ {"userId":1,"device":"Windows"}, {"userId":6,"device":"Windows"}, {"userId":5,"device":"Windows"} ], "Mac":[ {"userId":3,"device":"Mac"}, {"userId":4,"device":"Mac"} ], "Linux":[ {"userId":2,"device":"Linux"} ] }
How can we group them in this way?
There are two ways to do it like the below.
1. GroupBy to use Array.reduce()
The first way is grouping by using Array.reduce().
Sample code to group objects by a certain key.
/// Target object array. const logins = [ {userId:1, device:'Windows'}, {userId:3, device:'Mac'}, {userId:6, device:'Windows'}, {userId:2, device:'Linux'}, {userId:4, device:'Mac'}, {userId:5, device:'Windows'} ]; /// Group by device on object array const groupsByDevice = logins.reduce((result,current)=>{ if(result.hasOwnProperty(current.device)){ result[current.device].push(current) }else{ result[current.device] = [current]; } return result; }, {}); console.log(groupsByDevice);
The output of the above code :
{ "Windows":[ {"userId":1,"device":"Windows"}, {"userId":6,"device":"Windows"}, {"userId":5,"device":"Windows"} ], "Mac":[ {"userId":3,"device":"Mac"}, {"userId":4,"device":"Mac"} ], "Linux":[ {"userId":2,"device":"Linux"} ] }
In this example, they are grouped by the key ‘device’. However, fallback for cases where the object does not have the key ‘device’ is not taken into account, so devise this point on your own.
2. GroupBy to use Array.group()
The first way is grouping by using Array.group().
Caution : this method is experimental technology
What’s Array.group() ? :
The
group()
method groups the elements of the calling array according to the string values returned by a provided testing function. The returned object has separate properties for each group, containing arrays with the elements in the group.Quote : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/group
So easy method to grouping object array in JavaScript.
Sample code to group objects by using group() :
/// Target object array let logins = [ {userId:1, device:'Windows'}, {userId:3, device:'Mac'}, {userId:6, device:'Windows'}, {userId:2, device:'Linux'}, {userId:4, device:'Mac'}, {userId:5, device:'Windows'} ]; /// Group by device on objects const groupsByDevice = logins.group( ({ device }) => device ); console.log(
Unfortunately, this method is not yet available at of 2022/02/14.
Error occurs even in the latest Chrome :
FireFox, Edge, Safari, etc. are not yet supported.