Skip to content

chamara-madhu/group-by-name

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 

Repository files navigation

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

About

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)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published