What is the most effective way to group items in an array when they share a common key value in JavaScript?

I am looking to create a new array where objects are grouped based on a common key value pair.

For instance, starting with an Ungrouped Array:

let ugArray = [
   {name: 'jack', type: 'dog'},
   {name: 'brad', type: 'dog'},
   {name: 'ella', type: 'cat'},
   {name: 'lily', type: 'cat'},
   {name: 'rod', type: 'goat'},
]

The goal is to group the objects by their 'type' property resulting in the following output:

let groupedArray = [
   {dog: [
      {name: 'jack', type: 'dog'},
      {name: 'brad', type: 'dog'}
   ]},
   {cat: [
      {name: 'ella', type: 'cat'},
      {name: 'lily', type: 'cat'},
   ]},
   {goat: [
      {name: 'rod', type: 'goat'}
   ]}
]

Answer №1

Consider using an object instead of an array of objects for easier grouping:

let animalArray = [
   {name: 'jack', type: 'dog'},
   {name: 'brad', type: 'dog'},
   {name: 'ella', type: 'cat'},
   {name: 'lily', type: 'cat'},
   {name: 'rod', type: 'goat'},
];

let groupedAnimals = animalArray.reduce((result, obj) => {
  if (result[obj.type]) {
    result[obj.type].push(obj) 
  } else {
    result[obj.type] = [obj]
  }
  return result
}, {})

console.log(groupedAnimals)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do you understand why my Fabricjs canvas is rejecting a rectangle?

http://jsfiddle.net/a7ZSG/10/ check out the link to the jsfiddle for more information. Having trouble getting a red rectangle to appear in a green canvas? Can anyone figure out why it's not showing up? I've attempted using window.onload around a ...

Tips for invoking the setState method via an onClick event the ES6 way

class BlogPost extends React.Component{ //getInitialState constructor(){ super(); this.onLike = this.onLike.bind(this); this.state = { like :0 } } onLike(){ this.setState({ li ...

Angular directive ceases to trigger

I am currently working on implementing an infinite scrolling directive. Initially, when the page loads and I start scrolling, I can see the console log. However, after the first scroll, it stops working. It seems like it only triggers once. Can anyone poi ...

Angular fails to function properly post rendering the body using ajax

I recently created a HTML page using AJAX, and here is the code snippet: <div class="contents" id="subContents" ng-app=""> @RenderBody() @RenderSection("scripts", required: false) </div> <script src="http://ajax.googleapis.com/ajax/ ...

What are the best techniques for optimizing loops when inserting data into a database?

Hi there! Currently, I am facing a challenge in inserting data from an XML file into my MySql database using Sails.js and waterline for the queries. In my database schema, I have two tables named Users and Pets. A user can have multiple pets, and a pet can ...

What is the best way to efficiently set up a scrolling text ticker for repeated use?

I am currently utilizing GreenSock/TweenMax for the creation of scrolling text, inspired by the design seen on this webpage: If you're interested in learning more about Greensock and its capabilities, take a look at their documentation here: While I ...

Removing a contact from a telephone directory using C programming language

Struggling to remove a contact from my phone book code. All other functions are working fine, but deleting a contact is causing the program to stop. I've searched for different examples but haven't come across a solution that works for me. #inc ...

Newbie Programmer Alert: Utilizing Functions to Copy a Vector into an Array in C++

As a beginner, I am working to grasp the basics of functions, passing references, and vectors/arrays. In my code, I am reading a large data file into a vector. My current challenge is to convert this vector into an array, sort the array, and then display ...

Manipulating Python arrays with character or string values

As a newcomer to Python transitioning from environments like Java, C, and Haskell, I am curious if there is a way to achieve the following with strings instead of numbers. Currently, I have the code: for i in range(5, 11): print("Index : %d" % i) Thi ...

Obtain a matrix data from an Excel spreadsheet using c++ xll, make necessary modifications, and then return the

I have developed an xll function that takes a matrix from Excel, makes modifications, and returns it: __declspec(dllexport) LPXLOPER12 WINAPI ZZZZUpdateArray1(LPXLOPER12 arrayin) { if (arrayin->xltype == xltypeMulti | xlbitDLLFree) { do ...

Is there a way to "redirect" the user during the onbeforeunload event? If not, what is the alternative method to achieve this?

Can the browser be redirected to another page upon closing? Various Methods Tried: Attempted using onunload, but unsuccessful window.onunload = function redirect(){...} Another method tested, also unsuccessful: window.onbeforeunload = redirect(){ ...

Guide to fetching data from database based on selection in dropdown list using PHP and MySQL

Is there a way to retrieve information from a database and automatically populate a textarea field based on the option selected from a dropdown list using an onSelect event? You can view a screenshot of my form here. Basically, I want the description ass ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

Fancybox operates successfully when I manually include a class, yet fails to function when utilizing jQuery's .addClass() method

Below is a snippet of JS code that I use to add Fancybox classes to all hrefs on a webpage: $(function(){ //declaring target variable var $targetTable = $('.photo-frame a'); //looping through each table and adding the fancybox cla ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

Testing with Phantom/Casper in a browser-based environment

Currently, I am utilizing Casper for UI testing on websites. My main concern is regarding the compatibility testing in various browsers such as IE, Chrome, and Firefox using Casper. If this cannot be achieved with Casper, I am open to alternative methods ...

Cease running code post while loop (do not use break)

I need help with my code that checks if a user is already in a Database. Once the while Loop runs, it verifies the presence of the MC Player in their Database through the Mojang API. However, if the user is already in my Database, I want to skip the Mojang ...

Tips for creating animations using parent and child components in Angular

Despite my best efforts, it seems like this should be functioning properly... but unfortunately it's not... I'm attempting to achieve a transition effect on the parent element (ui-switch-groove) while the child element (ui-switch-dongle) moves. ...

What could be causing the Next.js error: WEBPACK_IMPORTED_MODULE function not being recognized?

I've hit a roadblock with an issue I can't seem to solve. I'm exporting a function that is supposed to provide the current authenticated user object, if available. I then use this user object to determine whether to add a navigation link. De ...

Ways to access information from a SQLite database using Angular

I am a beginner in front-end/back-end communication and I need guidance on how to retrieve data from a SQLite db file to populate a page in my Angular project. I have no idea where to begin, so any resources you can recommend would be greatly appreciated. ...