Using both strings and numbers in a Javascript array to simplify multidimensional reduction

I understand the concept of reduce, but I am struggling with a multidimensional array. Can someone help me with transforming this:

y = [['x', 0.5], ['x', 0.5], ['z', 2], ['z', 2]];

into this:

y = [['x', 1], ['z', 4]];

Appreciate any assistance!

Answer №1

One way to simplify the process is to use an object to accumulate the sums of keys, and then convert it back into an array of arrays using Object.entries()

const y = [
  ["x", 0.5],
  ["x", 0.5],
  ["z", 2],
  ["z", 2],
]

const res = Object.entries(
  y.reduce((acc, [key, value]) => {
    acc[key] = (acc[key] || 0) + value
    return acc
  }, {})
)

console.log(res)

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

Utilizing the NODE_ENV variable in a Windows 10 npm script

I have integrated webpack into a Typescript project. Following a helpful tutorial, I created 3 separate webpack configuration files: webpack.common.js webpack.production.js webpack.development.js In the tutorial's package.json, the "scripts" sectio ...

Retrieving a particular value from a JSON array using SQL syntax

Imagine having a table column filled with person data stored in a JSON array format, complete with categories and names. With SQL, it is possible to retrieve the information for a specific element in the array effortlessly: SELECT JSON_VALUE('{ " ...

Get the JSON array by decoding the JSON data in PHP

I have a JavaScript function that creates a JSON array and uses an AJAX post method. How should this JSON array be decoded on the PHP side? Here is my JavaScript function: var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"dat ...

Send form using AJAX with a callback function

I need help figuring out how to submit a form when a captcha is clicked. I attempted to use my own jQuery function, but unfortunately it's not working. Could someone please take a look at my code and let me know what's wrong with it? Javascript ...

What is the process for appending a file extension to a Next.js URL?

For instance, I am attempting to redirect the URL : https://example.com/data/publications to this : https://example.com/data/publications.json I made an attempt using Next.js redirection, but encountered difficulty when trying to add a string that does no ...

Incorporating Numerous Location Pointers in Angular-google-maps

I've been struggling to show multiple map markers in my Angular project. I have a service called retsAPI that queries a local MLS database for home listings, and I'm attempting to display these items on a Google map. Below is my controller code. ...

Get the file from the web browser

Hey there, greetings from my part of the world. I have some straightforward questions that I'm not sure have simple answers. Currently, I am working on a web application using the JSP/Servlet framework. In this app, users can download a flat text fil ...

Encountering Issue with Ionic Js After Upgrading Node to Version 4.1.1 on Windows Platform

Recently, I updated Node to version 4.1.1 and now I'm encountering an issue with Gulp: Error: libsass bindings not found. Have you tried reinstalling node-sass? I've attempted various solutions to no avail, including: Removing node_modules an ...

The autocomplete feature is not displaying the data in the Bootstrap modal, only the list is visible

Having trouble with autocomplete in the bootstrap modal. The search for a book only shows black dots. Any solutions to this issue? As shown in the image, I've attempted to use CSS z-index but the problem persists. https://i.sstatic.net/e1ga9.png publi ...

What is the best method to evaluate lambda functions in a functional React Component using Jest and Enzyme?

My current challenge involves creating a pulldown tab in a TDD style. I have been struggling to test if the function inside the component triggers on the button's click event. The jest logs keep showing me errors indicating that the object I'm tr ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

What does the curly braces {} signify in the JavaScript programming language

While delving into sample code, I came across a line that left me puzzled. var foo = {}; From my observations, it seems like this is being used as a type of array where the index is a string provided by the user instead of traditional numerical indexes. ...

Is it possible to establish a default route in Next.js?

Is it possible to set up default routes in Next.js so that all routes, or a specific list of routes, will automatically navigate to a designated page? My project involves using Next.js to create the marketing website, as well as the sign-up and sign-in pr ...

Is there a bug in Firefox concerning the accuracy of document.body.getBoundingClientRect().top?

When I access Firefox version 17.0.1 and request document.body.getBoundingClientRect().top; on a simple site with no CSS styling applied, it returns an incorrect value. Instead of the expected 8, which is the default for the browser, it shows 21.4. However ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Pulling down the data with Ajax "GET"

When a user clicks on a button, a zip file will be downloaded. I have the necessary components in place, but I am struggling to ensure they work together seamlessly. The "GET" call will retrieve byte content with the content type specified as application/ ...

Empty canvas when Material UI Modal transitions states

I've been struggling to make a simple modal using material UI, but every time I try to change the state, it just shows a blank white page. Can anyone help me figure out why this is happening? Here's the code snippet: import {Button,Modal} fro ...

Data retrieval takes precedence over data insertion

I'm facing an issue where I am trying to insert data into MySQL using Knex within a loop, but the data retrieval is happening before the insertion. Can anyone assist me with this problem? for (let i = 0; i < fileArray.length; i++) { fileLocation ...

Center the popover over the element

I am in the process of creating a resource map using SVGs. My goal is to display a popover in the center of the element when a user clicks on it. However, due to CSS rotation of the map, the traditional techniques such as the one mentioned here have not be ...