What is the best way to organize an array of objects into distinct arrays based on their values?

For example:

array  = [{name:'Anna'}, {name:'Bob'}, {name:'Joe'}, {name:'Anna'}]

I am looking to group this array based on the name attribute in order to create separate arrays like:

array 1 = [{name:'Anna'}, {name:'Anna'}]
array 2 = [{name:'Joe'}]
array 3 = [{name:'Bob'}]

Any suggestions on how I can achieve this? Thank you!

Answer №1

To organize the items by name rather than sorting them is what you seem to be looking for.

If this is your goal, one approach is to create an intermediate dictionary using Array.reduce(). In this dictionary, the keys represent names and the values consist of arrays that group all objects with the same name together.

After that, utilize Object.values() to iterate through this dictionary and retrieve all groups:

const arr = [{name:'Anna', hello: 1}, {name:'Bob'}, {name:'Joe'}, {name:'Anna'}];

const result = Object.values(arr.reduce((acc, x) => {
  acc[x.name] = [...(acc[x.name] || []), x ];
  return acc;
}, {}));

console.log(result)

Answer №2

To effectively group your array based on the 'name' key and extract the object values, you can utilize the Array.reduce method along with Object.values.

var data  = [{name:'Anna'}, {name:'Bob'}, {name:'Joe'}, {name:'Anna'}];

const result = data.reduce((accumulator, item) => {
   if (accumulator[item.name]) {
      accumulator[item.name] = [...accumulator[item.name], item];
   } else {
      accumulator[item.name] = [item];
   }
   return accumulator;
}, {});

console.log(Object.values(result));

Answer №3

To transform the array into an object based on a specific value, simply utilize the reduce method like so:

const result = array.reduce((accumulator, element) => {
  if (!accumulator[element.name]) {
    return {
       ...accumulator,
       [element.name]: [element]
    }
  }
  return {
    ...accumulator,
    [element.name]: [...accumulator[element.name], element]
  }
}, {});

This will give you an object where each field contains an array of elements as requested.

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

Avoid retrieving data during the fetching process

I have been working on an application that utilizes Redux for state management. Furthermore, I have been using the native fetch method to fetch data. return fetch("https://dog.ceo/api/breeds/image/random").then(res => res.json()); Within my React co ...

Can you provide any methods for enhancing a pre-existing jQuery event handler?

I have developed a code that resets the form and clears it each time the reset event occurs like this: $("form").on("reset", function(event) { event.preventDefault(); $("form").clearForm(); $("#reportGenerated").empty(); }); This code is stor ...

"Unleashing the fun: incorporating a variety of random songs into your

My goal is to create a central button on my webpage that, when clicked, will trigger a playlist of randomly selected songs. Once pressed, this button should vanish, giving way to an audio control window that spans the full width of the screen at the bottom ...

Obtain the context within the image loading function

I am working with an array of Image objects: let imageArray = []; ... imageArray[i].onload = function () { ... } When the onload function is triggered, I need to determine which specific Image object it is referring to. Is there a method to achieve ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application ...

Personalized cursor that blinks while utilizing window.history.replaceState

While navigating between sub-pages, I utilize the window.history.replaceState method to replace URLs in my web application. However, I have noticed that my custom cursor briefly blinks (replaced by cursor: default) when the current URL is replaced with a n ...

Checklist options controlled by dropdown menus

I am facing a challenge with a collection of checkboxes that represent settings for equipment displayed on a page. The checkboxes are populated using ObjectdataSource and an IEnumerable method to bring distinct settings. Additionally, I have created a drop ...

Is there a more efficient method to achieve this task using JavaScript or jQuery?

Here is the code snippet I am currently using: $(document).ready(function() { //Document Ready $(".examples .example1").click(function() { $(".examples .example1 div").fadeToggle("slow"); $(".examples .example1").toggleClass('focused') ...

Error in Console while Json is not being displayed on the Screen in React Native

Encountering an issue while attempting to display JSON data from mongodb on the screen of a React Native Application. The screen is visible but no data is showing up. Below is the error message along with the code snippet. This is a basic hello world appli ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

Passport not retaining session when used with a proxy server

Situation Currently, my frontend is built using React and the backend server utilizes SAML authentication process with Azure AD, which is handled by an Express server. The nginx server serves the React application and acts as a proxy passing all requests ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...

Vue3 - Utilizing a method to dynamically alter an input property

Currently, I am in the process of developing a Vue application that incorporates a map feature. The main functionality involves determining whether a given position on the map is over water or land. If the position is over water, I want to iterate through ...

Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component. Alth ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

Guide on how to choose a radio button in IONIC with the help of angularJS

<ion-list> <ion-radio ng-model="choice" ng-value="'A'" ng-click='usedGNG("yes")'>Yes</ion-radio> <ion-radio ng-model="choice" ng-value="'B'" ng-click='usedGNG("no")'>No</ion-radio> </ ...

React-select: issue with maintaining selected option on input

Hello everyone, I am new to React and seeking some assistance in reviewing my code. I have a component called Bucket that contains multiple challenges as separate components. Here is a simplified version of the code: class CLL_Bucket extends Component { ...

Prioritize returning AJAX data over iterating through the parent loop

Hey everyone, I'm having trouble wrapping my head around this issue even after researching various scenarios online. Here's what's going on: I have an array of strings named recipientsList. What I want to do is make an AJAX call for each s ...