Skip to content

Group array of objects by Key in JavaScript

Find out how to group an array of objects by key in JavaScript. In JavaScript, we can make use of reduce method of array object to group elements of the array by a particular key.

I have an array of objects like the one below. I would like to group this array by the key ‘date’.

[{
	"message": "Hello  hello  Corona world!",
	"team": "Admin",
	"sentBy": "Anand Kumar",
	"date": "Wednesday, April 8, 2020",
	"time": "8:54 PM"
}, {
	"message": "Hello Admins  I need a help. Please call me @ 181-892-676",
	"team": "Admin",
	"sentBy": "Anand Kumar",
	"date": "Wednesday, April 8, 2020",
	"time": "8:55 PM"
}, {
	"message": "Hello Team  Good afternoon. Can someone send me the status please?",
	"team": "Admin",
	"sentBy": "Anand Kumar",
	"date": "Wednesday, April 9, 2020",
	"time": "12:04 PM"
}, {
	"message": "Hmm?",
	"team": "Admin",
	"sentBy": "Anand Kumar",
	"date": "Wednesday, April 9, 2020",
	"time": "12:10 PM"
}]

To group an array by a specific key, we can use the following code. Pass the array and the key.

const groupBy = (array, key) => {
    // Return the reduced array
    return array.reduce((result, currentItem) => {
      // If an array already present for key, push it to the array. Otherwise create an array and push the object.
      (result[currentItem[key]] = result[currentItem[key]] || []).push( currentItem );
      // return the current iteration `result` value, this will be the next iteration's `result` value and accumulate
      return result;
    }, {}); // Empty object is the initial value for result object
  };

The output would look like..

{
	"Wednesday, April 8, 2020": [{
		"message": "Hello  hello  Corona world!",
		"team": "Admin",
		"sentBy": "Anand Kumar",
		"date": "Wednesday, April 8, 2020",
		"time": "8:54 PM"
	}, {
		"message": "Hello Admins  I need a help. Please call me @ 181-892-676",
		"team": "Admin",
		"sentBy": "Anand Kumar",
		"date": "Wednesday, April 8, 2020",
		"time": "8:55 PM"
	}],
	"Wednesday, April 9, 2020": [{
		"message": "Hello Team  Good afternoon. Can someone send me the status please?",
		"team": "Admin",
		"sentBy": "Anand Kumar",
		"date": "Wednesday, April 9, 2020",
		"time": "12:04 PM"
	}, {
		"message": "Hmm?",
		"team": "Admin",
		"sentBy": "Anand Kumar",
		"date": "Wednesday, April 9, 2020",
		"time": "12:10 PM"
	}]
}
See also  Capitalize the first letter of every word in a string in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.