group-by-name
v2.5.2
Published
Group array objects by an object key
Downloads
26
Readme
group-by-name
Here's a simple grouping function in JavaScript that you can use to group an array of objects by an attribute (in this case, the "name" attribute):
Install
npm install group-by-name
Usage
groupByName(array, name);
array - input array. name - object key name (attribute name);
Input:
const cars = [
{
make: "BMW",
modal: "X1",
capacity: "2000cc",
},
{
make: "Benz",
modal: "E300",
capacity: "3000cc",
},
{
make: "BMW",
modal: "X6",
capacity: "2500cc",
},
];
Invoke:
const groupByName = require("group-by-name");
const output = groupByName(cars, "make");
Output:
[
{
name: "BMW",
data: [
{ make: "BMW", modal: "X1", capacity: "2000cc" },
{ make: "BMW", modal: "X6", capacity: "2500cc" },
],
},
{
name: "Benz",
data: [{ make: "Benz", modal: "E300", capacity: "3000cc" }],
},
];
License
ISC © chamaramadhushanka