JavaScript Group By Array

Asked
Active3 hr before
Viewed126 times

9 Answers

javascriptarray
90%

It doesn't require any libraries (unlike e.g. _.groupBy()),You can do it with Alasql JavaScript library:,You get a JavaScript Map rather than an object (e.g. as returned by _.groupBy()). This has lots of benefits, including: it remembers the order in which items were first added, keys can be any type rather than just strings. , Grunt doesn't like it, that make it crashes.. – Francois Girard Aug 19 at 15:09

var groupBy = function(xs, key) {
   return xs.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
   }, {});
};

console.log(groupBy(['one', 'two', 'three'], 'length'));

// => {3: ["one", "two"], 5: ["three"]}
load more v
88%

In this article, I will explain about the groupBy array of object in javascript.,I will explain this using one example.,The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.,The output should be like this.

I will explain this using one example.

const cars = [{
   make: "audi",
   model: "r8",
   year: "2012"
}, {
   make: "audi",
   model: "rs5",
   year: "2013"
}, {
   make: "ford",
   model: "mustang",
   year: "2012"
}, {
   make: "ford",
   model: "fusion",
   year: "2015"
}, {
   make: "kia",
   model: "optima",
   year: "2012"
}];
load more v
72%

We now want to group this array. We can do this by artist, or by year.,The groupBy function takes a key (eg: 'year') as its only argument, and returns another function group, which in turn takes the array of objects that we'd like to sort.,Within the group function, we're reducing the array using an empty object as the accumulator (because that's the shape of the final result we're after).,New JavaScript and Web Development content every day. Follow to join our +2M monthly readers.

Explanation

Our groupBy function is a curried function that makes use of partial application to help keep this function re-usable.

groupBy
load more v
65%

The most efficient method to group by a key on an array of objects in js is to use the reduce function.,Most efficient method to groupby on an array of objects - JavaScript,What is the most efficient string concatenation method in python?,The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Example

const people = [{
      name: 'Lee',
      age: 21
   },
   {
      name: 'Ajay',
      age: 20
   },
   {
      name: 'Jane',
      age: 20
   }
];

function groupBy(objectArray, property) {
   return objectArray.reduce((acc, obj) => {
      const key = obj[property];
      if (!acc[key]) {
         acc[key] = [];
      }
      // Add object to list for given key's value
      acc[key].push(obj);
      return acc;
   }, {});
}
const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);
load more v
75%

To write a function that will group an array of objects by its key value, you need to use the array reduce() method to iterate over the array and put each array element into the right place.,Then, you need to call the reduce() method on the arr variable, with an empty object {} as the accumulator’s starting value:,How to write a custom function that groups an array of objects by key or property,First, create a function named groupBy() that accepts an array and a string. In the following code example, the parameter arr is for passing the array of objects, while criteria will be for the property which the elements will be grouped by:

const movies = [{
      title: "Sonic the Hedgehog",
      year: 2020
   },
   {
      title: "Mulan",
      year: 2020
   },
   {
      title: "Godzilla vs. Kong",
      year: 2021
   },
];

const moviesByYear = groupBy(movies, "year"); // TODO: implement groupBy()
load more v
40%

create an object as initial value for our result object,inside the array reduce, create an array for each distinct key value and push the currentValue if the key value present in the currentValue,Lets see an usual example of array reduce,,Hope you learned a trick of how to use array reduce and also how to create groupBy function using array reduce 😎

// Person array with name and Age
const person = [{
      name: 'Jim',
      color: 'blue',
      age: 22,
   },
   {
      name: 'Sam',
      color: 'blue',
      age: 33,
   },
   {
      name: 'Eddie',
      color: 'green',
      age: 77,
   },
];

// Add their sum of ages
const sumOfAges = person.reduce((sum, currentValue) => {
   return sum + currentValue.age;
}, 0);

console.log(sumOfAges); // 132
load more v
22%

The countBy function is one of the functions why people use Lodash in their JavaScript code base. Here I want to give you a brief example on how to implement countBy in vanilla JavaScript without…,The groupBy function is one of the functions why people use Lodash in their JavaScript code base. Here I want to give you a brief example on how to implement groupBy in vanilla JavaScript without Lodash by just using JavaScript's reduce method.,The Map Function is one of the many Methods existing on the JavaScript Array prototype . If you want to do a deep dive on prototypical inheritance, here's a great read by Kyle Simpson on how…,The groupBy in JavaScript is done. Here again with comments for both steps:

Let's say we have the following and we want to group them by property (here color) to get the following output:

const users = [{
   name: 'Jim',
   color: 'blue'
}, {
   name: 'Sam',
   color: 'blue'
}, {
   name: 'Eddie',
   color: 'green'
}, ];
const usersByColor = // TODO: implement groupBy console.log(usersByColor); // {//   blue: [{//     { name: 'Jim', color: 'blue' },//     { name: 'Sam', color: 'blue' },//   }],//   green: [{ name: 'Eddie', color: 'green' }]// }
const users = [{
   name: 'Jim',
   color: 'blue'
}, {
   name: 'Sam',
   color: 'blue'
}, {
   name: 'Eddie',
   color: 'green'
}, ];
const usersByColor = // TODO: implement groupBy console.log(usersByColor); // {//   blue: [{//     { name: 'Jim', color: 'blue' },//     { name: 'Sam', color: 'blue' },//   }],//   green: [{ name: 'Eddie', color: 'green' }]// }

We can use JavaScript's reduce method on an array to iterate over every item:

const usersByColor = users.reduce((acc, value) => { // TODO: implement groupBy   return acc;}, {});
const usersByColor = users.reduce((acc, value) => { // TODO: implement groupBy   return acc;}, {});

We start with an empty object as our accumulator (here acc) for this reduce's . For every iteration of the function, we return the changed (here still unchanged) accumulator. Let's implement groupBy:

const usersByColor = users.reduce((acc, value) => {
         if (!acc[value.color]) {
            acc[value.color] = [];
         } // TODO: implement grouping   return acc;}, {});
const usersByColor = users.reduce((acc, value) => {
         if (!acc[value.color]) {
            acc[value.color] = [];
         } // TODO: implement grouping   return acc;}, {});

If the accumulator has no array initialized for the currently iterated value's color, we create an empty array for it allocated in the object whereas the color is the key. Afterward, we can assume that there is an array for the color and just push the value to it:

const usersByColor = users.reduce((acc, value) => {
   if (!acc[value.color]) {
      acc[value.color] = [];
   }
   acc[value.color].push(value);
   return acc;
}, {});
const usersByColor = users.reduce((acc, value) => {
   if (!acc[value.color]) {
      acc[value.color] = [];
   }
   acc[value.color].push(value);
   return acc;
}, {});

The groupBy in JavaScript is done. Here again with comments for both steps:

const usersByColor = users.reduce((acc, value) => { // Group initialization  if (!acc[value.color]) {    acc[value.color] = [];  }   // Grouping  acc[value.color].push(value);   return acc;}, {});
const usersByColor = users.reduce((acc, value) => { // Group initialization  if (!acc[value.color]) {    acc[value.color] = [];  }   // Grouping  acc[value.color].push(value);   return acc;}, {});
load more v
60%

and I want to convert this array in to this array,@JamieMason empty objects was just an example sorry for confusing you. , let assume I have a data,Just for fun, if you were to do the same using Array and Object functions, the equivalent would look like this:,Here's a way to do it in TypeScript:

const groupBy = key => array =>
   array.reduce((objectsByKeyValue, obj) => {
      const value = obj[key];
      objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
      return objectsByKeyValue;
   }, {});
load more v
48%

Search Answer Titles

function groupArrayOfObjects(list, key) {
   return list.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
   }, {});
};

var people = [{
      sex: "Male",
      name: "Jeff"
   },
   {
      sex: "Female",
      name: "Megan"
   },
   {
      sex: "Male",
      name: "Taylor"
   },
   {
      sex: "Female",
      name: "Madison"
   }
];
var groupedPeople = groupArrayOfObjects(people, "sex");
console.log(groupedPeople.Male); //will be the Males 
console.log(groupedPeople.Female); //will be the Females
load more v

Other "javascript-array" queries related to "JavaScript Group By Array"