js categorize elements in array based on their value

Looking to organize values together that share the same value within an array

[ [ [ "Mangas", 23809.132685271947 ], [ "Magazines", 2162.858571621124 ], [ "Journal", 0 ], [ "Livres", 2533.654678438289 ] ], [ [ "Mangas", 25809.508799386324 ], [ "Magazines", 2519.527899187236 ], [ "BDs", 0 ], [ "Livres", 2436.7144208655627 ] ] ]

desired output (or similar)

[ 
[ [ "Mangas", 23809.132685271947 ], [ "Mangas", 25809.508799386324 ] ],
[ [ "Magazines", 2162.858571621124 ], [ "Magazines", 2519.527899187236 ] ],
[ [ "Livres", 2533.654678438289 ], [ "Livres", 2436.7144208655627 ] ],
[ [ "Journal", 0 ] ],
[ [ "BDs", 0 ] ]
]

Experimenting with various methods (groupBy, groupByToMap, etc)

thank you so much!!

Answer №1

To start, let’s organize similar elements into an associative array. Next, structure the response in the desired format.

var data = [ [ [ "Apples", 20 ], [ "Bananas", 10 ], [ "Oranges", 0 ], [ "Grapes", 25 ] ], [ [ "Apples", 30 ], [ "Bananas", 15 ], [ "Pears", 0 ], [ "Grapes", 30 ] ] ];

let groupedData = {};
for (let group1 of data) {
    for (let group2 of group1) {
        if (groupedData[group2[0]]) {
            groupedData[group2[0]].push(group2);
        } else {
            groupedData[group2[0]] = [group2];
        }
    }
}
let finalData = [];
for (let key in groupedData) {
    finalData.push(groupedData[key]);
}
console.log(finalData);

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

What causes the difference in behavior between using setInterval() with a named function as an argument versus using an anonymous function?

I can't seem to figure out why using the function name in setInterval is causing issues, while passing an anonymous function works perfectly fine. In the example that's not working (it's logging NaN to the console and before the first call, ...

Bring in a node module into a Vue.js CLI session

I recently set up a fresh Vue application by running vue init webpack sample-app. My goal is to incorporate the module found at this link () into my app.vue and display it correctly. Could someone guide me on the proper method to import this module into ...

Are routes in Next.js easy for search engines to crawl?

Currently, I am developing a movie application using NextJS to enhance my skills. The homepage features each movie's title and a brief description. When a user clicks on a movie, they are taken to a dedicated page that showcases more details about the ...

Show angular variable data in a table based on their index

I have an array of angular variables with values like [ 170, 1, 130, 3, 134, 4.... and so on]. I would like to present these values in a table format where the even positioned values are shown in one column and the odd positioned values in another column. ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...

Launching a new window and displaying content across 2 separate tabs

Currently, I am incorporating both angular js and javascript within my application. An issue that has arisen is that when I click on the <a> tag, it triggers a method in an angular controller which contains $window.open();. The problem lies in the fa ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

Consolidate duplicate list entries and adjust the CSS as needed

Imagine I have an array like this: myarray = ["apple", "apple", "apple", "potato", "apple"]; myarray = ["apple", "apple", "apple", "potato", "apple"]; function listCreate(data) { var output = '<ul>'; $.each ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

issue encountered when attempting to use string.replace with regex

When using a regex like this: I am attempting to replace "subdir" with a custom string using the string.replace method. However, when I use myStr.replace(/^.*\/\/.*\.net\/.*\/(.*)\/.*\z/, otherStr) The result is not as ...

Utilizing Vuejs to Modify Laravel Pivot (BelongsToMany) Table

My VueJs form is set up like this, using v-model: <select name="service_id" v-model="client.services[0].pivot.service_id"> <option v-for="service in services" v-bind:key="service.id" v-bind:value=" ...

Combining 2 objects in vue.js that share a common field name

Currently, I am attempting to merge two objects based on a shared key, specifically when they have two fields with the same name but differing values. var players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : &quo ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

Node.js tip: track down and address ignored errors in your code

Is there a method in node.js to track and log all exceptions? I find process.on('uncaughtException') insufficient for my needs, as I want to log all handled and unhandled exceptions, even if they were caught and disregarded using a catch block s ...

Deleting a specific element in React: Step-by-step guide

Having an issue with the handleDelete() method in DisplayList.JSX where it is deleting the first element instead of the selected element. How can this be resolved? Github Display.jsx import {DisplayList} from './DisplayList'; class Display e ...

Adjust the container size based on changes in font size

One interesting issue I encountered involves displaying each word in a sentence in separate div elements using inline-block with a max-width of 120px. When attempting to increase the font size within the parent div, the inline-block divs begin to overlap d ...

The npm error message states: "Unable to locate the 'readable-stream' module."

Recently, I installed node js on my Windows 10 machine with version v4.4.2. However, whenever I attempt to run npm install or check npm version, it throws the following error message. Any assistance on this matter would be highly appreciated. Error: Canno ...

Utilize pivot to manage user roles and permissions in ExpressJS application using Mongoose

My user schema is structured as shown below const userSchema = mongoose.Schema({ username: { type: String, required: true, }, first_name: { type: String, required: true, }, last_name: { type: Stri ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...