Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck

Array:

list = [
    {id: "0", created_at: "foo1", value: "35"},
    {id: "1", created_at: "foo1", value: "26"},
    {id: "2", created_at: "foo", value: "13"},
    {id: "3", created_at: "foo1", value: "11"},
    {id: "4", created_at: "foo", value: "11"},
    {id: "5", created_at: "foo1", value: "16"},
    {id: "6", created_at: "foo", value: "26"},
    {id: "7", created_at: "foo1", value: "13"},
    {id: "8", created_at: "foo1", value: "16"}
];

The desired result should look like this:

var result = [
    [
        {id: "0", created_at: "foo1", value: "35"}
    ],
    [
        {id: "1", created_at: "foo1", value: "26"},
        {id: "6", created_at: "foo", value: "26"}
    ],
    [
        {id: "2", created_at: "foo", value: "13"},
        {id: "7", created_at: "foo1", value: "13"}
    ],
    [
        {id: "3", created_at: "foo1", value: "11"},
        {id: "4", created_at: "foo", value: "11"}
    ],
    [
        {id: "5", created_at: "foo1", value: "16"},
        {id: "8", created_at: "foo1", value: "16"}
    ]         
];

Does anyone have any suggestions on how to achieve this? Thank you in advance.

Just a reminder: I am utilizing angular 5 framework.

Answer №1

If you're looking into utilizing Lodash for this task, you have the option to employ _.groupBy:

var data = [
    {id: "0", created_at: "foo1", value: "35"},
    {id: "1", created_at: "foo1", value: "26"},
    {id: "2", created_at: "foo", value: "13"},
    {id: "3", created_at: "foo1", value: "11"},
    {id: "4", created_at: "foo", value: "11"},
    {id: "5", created_at: "foo1", value: "16"},
    {id: "6", created_at: "foo", value: "26"},
    {id: "7", created_at: "foo1", value: "13"},
    {id: "8", created_at: "foo1", value: "16"}
];

var result = _.groupBy(data, 'value');

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

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

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Ways to streamline redundant code by creating a higher order function that accepts different parameter types in TypeScript

Recently, I've been exploring the idea of refactoring this code into a higher order function using TypeScript to enhance its cleanliness and reusability. However, I'm facing quite a challenge in getting it to work seamlessly. import { DocumentDef ...

How can you set a $_GET variable without having to reload the page?

I have a table on my website that displays values for each row, and here's an example code snippet: //JAVASCRIPT <tr onclick="window.history.replaceState(null, null, 'myPage.php?ID=2');"> The URL changes with this code, but it doesn& ...

Tips for effectively handling the auth middleware in react.js by utilizing LocalStorage

After making a call to the authentication API, the plan is to save the authentication token in LocalStorage and then redirect to a dashboard that requires token validation for entry. However, an issue arises where the authentication token isn't immedi ...

The response type for HTTP Get in Typescript is specified as "text"

I'm currently working on a Typescript HTTP Get request and need to customize the response type as text. Here's my code snippet: getMessageContent(messageContentId?: string): Observable<string> { const url = this.commonService.getApi ...

The functionality of the button is disabled once a pop-up JavaScript is implemented

I have encountered an issue with my HTML code that involves a button intended to hide certain content. The problem arose when I implemented a popup feature, causing the button to malfunction. Here is the JavaScript for the popup: $ = function(id) { retur ...

Generating a dynamic optional parameter for deduced generics

I have a specific object with the following structure: { first: (state: S, payload: boolean) => { payload: boolean, type: string }, second: (state: S) => { payload: undefined, type: string }, } My goal is to manipulate this object by removing th ...

A guide on accessing JavaScript files from the components directory in a React Native iOS application

I am encountering difficulty in accessing the components folder within my React Native Project on IOS. The error message I am receiving is: Unable to resolve module ./Login from ....../ReactNative/ReactNativeProject/components/App.js: Unable to find ...

Modified the object path and updated the Dirty stages for nested objects within Vue state

Imagine having an object that contains arrays of objects in some properties. Whenever changes are made to any field, whether it's within an object in an array or the main object itself, you want to mark that object as "dirty" using a code snippet like ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

Enhancing game menus for various mobile screen sizes

I've noticed a consistent pattern in the games I download from the Google Play Store - they all have a background image at the menu with clickable buttons. When testing these games on different devices, I found that the backgrounds didn't stretch ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

Assign a unique CSS style to each Popper

I am currently working on a component that generates 6 unique experiences, each with its own popper. My goal is to customize the styles of each popper in terms of background and position, and ensure that all poppers display images of the same size. Despite ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

Implement pop-up functionality on additional buttons. Modify existing code to accommodate multiple buttons

I have a feature that allows me to click on a button and trigger a pop-up window with the desired content. The issue I am facing is how to duplicate this functionality for multiple buttons, each triggering a different pop-up content. I attempted to duplic ...

The browser is struggling to interpret the incorrect HTML content

I am looking for a way to create a function that can retrieve account data from my database and organize it in a user-friendly HTML table where users can make selections and modifications. The code I have so far is as follows: $.ajax({ url: "./dat ...

Benefits of Utilizing Sets in Ruby

One key advantage of using a Set is its ability to maintain unique elements. However, achieving the same in an Array is simple with, array = [2,3,4] array | [2,5,6] # => [2,3,4,5,6] The only distinctive feature I've encountered (which may be rele ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

Fixing PNG Fading Issue in Internet Explorer 8

I am currently utilizing the jQuery Cycle plugin to produce a fading animation effect. While this works perfectly on most browsers, I have encountered an issue with PNG files containing semi-transparent pixels in Internet Explorer 8. These partially transp ...