Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations.

The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearrange it so that it is grouped by location and appears like this

{ location: Location, data: T[]}>[]

Initially, my approach involved using _.GroupBy

const entitiesMap = entities.map(e => ({ location: this.options.locationResolver(e), data: e}));
this.locationEntitiesMap = _.groupBy(entitiesMap, entityPair => entityPair.location);

However, upon implementation, I noticed that this method returns an object with the location as the Key. How can I modify this to return a grouped array instead?

Answer №1

One efficient way to handle this task is by utilizing a reduce function.

const places = [
  { location: {id: 'USA'},  data:{ eventName:'tech week' }},
  { location: {id: 'GER'},  data:{ eventName:'cheese wheeling' }},
  { location: {id: 'USA'},  data:{ eventName:'mecha fights' }},
  { location: {id: 'AUS'},  data:{ eventName:'kangaroo fight' }}
];

const group = (array, prop) => array.reduce((g, item) => {
    const propVal = item[prop];
    const identifier = propVal.id;
    const entry = g[identifier];
    const data = item.data;

    if (entry) {
      entry.data.push(data);
    } else {
      g[identifier] = {location: propVal, data: [data]};
    }
    return g;
  }, {});

const groups = group(places, 'location');
console.log(group(Object.keys(groups).map((key) => groups[key]), 'location'));

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

Error in Angular 4: Unexpected 'undefined' provided instead of a stream

I encountered an issue while attempting to make a HTTP Post request. The error message I received is as follows: auth.service.ts?c694:156 Something went wrong requesting a new password, error message: You provided 'undefined' where a stream ...

Click on the div to automatically insert its text into the textarea

I am looking for a way to enable users to edit their posts easily. My idea is to have them click on a link, which will then hide the original div containing their post and reveal a new div with the old text inside a textarea for editing. Despite searching ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

You are required to select one of the two radio buttons in order to proceed with the validation process

To prevent the user from proceeding to the next page, validation is necessary. They are required to select one of the radio buttons, etc. <div class=""> <div class="radiho" style="display: block"> <input type="checkbox" name="sp ...

Distribute among an array of specific types

I am trying to achieve this behavior using Typescript: type animals = 'cat' | 'dog' let selectedAnimals: animals[] = ['cat'] selectedAnimals = [ // <- Type 'string[]' is not assignable to type 'animals[]&ap ...

Error: The StsConfigLoader provider is not found! MSAL angular

I am currently using Auth0 to manage users in my Angular application, but I want to switch to Azure Identity by utilizing @azure/msal-angular. To make this change, I removed the AuthModule from my app.module and replaced it with MsalModule. However, I enco ...

From integrating Vue 2 TSX to React TSX: ensuring seamless cooperation

Currently, my app is built with Vue 2 using vue-tsx-support, vue-class-component, and vue-property-decorator. All of my Vue 2 components are already TSX classes. I am interested in gradually transitioning to React. I experimented with https://github.com/ ...

Determine parameter types and return values by analyzing the generic interface

I am currently working on a feature where I need to create a function that takes an interface as input and automatically determines the return types based on the 'key' provided in the options object passed to the function. Here is an example of ...

Find the mean of two values entered by the user using JavaScript

I'm sorry for asking such a basic question, but I've been struggling to get this code to work for quite some time now. I'm ashamed to admit how long I've spent trying to figure it out and how many related StackOverflow questions I ...

What is the process for setting up a resthook trigger in Zapier?

I'm currently integrating Zapier into my Angular application, but I'm struggling with setting up a REST hook trigger in Zapier and using that URL within my app. I need to be able to call the REST hook URL every time a new customer is created and ...

Uncovering the Magic: Retrieving the Value of an Adaptable Form in Angular

I'm attempting to retrieve the value from a dynamic form that contains multiple resources retrieved from a database. My goal is to modify three parameters, C, I, and A, for each resource. However, the form group always returns the value of the last re ...

Unexpected behavior observed in while loop with dual conditions

To break the while loop, I need two conditions to be met - res must not be undefined, which only happens when the status code is 200, and obj.owner needs to match a specific value I have set. Since it takes a few seconds for the owner on that page to updat ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Using default JavaScriptSerializer to bind DateTime to knockout view model

Recently, I started using knockout and encountered a problem with DateTime Serialization and Deserialization when using the JavaScriptSerializer. I modified the gifts model in Steve's koListEditor example from his blog to include a new field for Modi ...

Check the validity of a watched variable's value and block any assignments that do not meet the specified requirements without triggering the watch function

Check out my jsBin snippet here I am experimenting with watching a variable's value and handling failed validation by returning its previous value without triggering the watch function again. I am considering the following scenario: If validation ...

Utilizing a combination of CSS and JavaScript, the traffic light can be altered to change based on

**I stumbled upon this online code snippet where a timer is controlled in CSS. I'm trying to figure out how to control it with JavaScript, but all my attempts have failed so far. Is there anyone who can help me solve this issue? What I'm attempti ...

How can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

How to extract the values of the parent for a specific child within an array of nested JSON objects?

Take a look at this snapshot of my JSON data. const info = [{ "employees": [ { "employee": [ { "name": "Jon", "surname": "Smith&quo ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Moving an array in AngularJS from one file to another

As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...