What is the best way to combine these arrays?

Having trouble finding the most efficient solution to this problem. I attempted using a loop, but I can't seem to make any progress. Any assistance would be greatly appreciated.

This is my current data:

[ [ ‘TWENTY’, 2000 ],
[ ‘TWENTY’, 2000 ],
[ ‘TWENTY’, 2000 ],
[ ‘TEN’, 1000 ],
[ ‘TEN’, 1000 ],
[ ‘FIVE’, 500 ],
[ ‘FIVE’, 500 ],
[ ‘FIVE’, 500 ],
[ ‘ONE’, 100 ],
[ ‘QUARTER’, 25 ],
[ ‘QUARTER’, 25 ],
[ ‘DIME’, 10 ],
[ ‘DIME’, 10 ],
[ ‘PENNY’, 1 ],
[ ‘PENNY’, 1 ],
[ ‘PENNY’, 1 ],
[ ‘PENNY’, 1 ] ]

I am aiming for:

[ [ ‘TWENTY’, 6000 ],
    [ ‘TEN’, 2000 ],
    [ ‘FIVE’, 1500 ],
    [ ‘ONE’, 100 ],
    [ ‘QUARTER’, 50 ],
    [ ‘DIME’, 20 ],
    [ ‘PENNY’, 4 ] ]

My attempt at solving it so far:

newArr = [ [ 'TWENTY', 0 ],
    [ 'TEN', 0 ],
    [ 'FIVE', 0 ],
    [ 'ONE', 0 ],
    [ 'QUARTER', 0 ],
    [ 'DIME', 0 ],
    [ 'PENNY', 0 ] ];

for (var z = 0; z < arr.length; z++) {
  for (var y = 0; y < newArr.length; y++) {
    if (newArr[y][0] == arr[z][0]) {
    newArr[y][1] =  newArr[y][1] + arr[z][1]
    }
  }

}

Answer №1

Check out the code snippet below for the solution:

const arr = [['TWENTY', 2000],
['TWENTY', 2000],
['TWENTY', 2000],
['TEN', 1000],
['TEN', 1000],
['FIVE', 500],
['FIVE', 500],
['FIVE', 500],
['ONE', 100],
['QUARTER', 25],
['QUARTER', 25],
['DIME', 10],
['DIME', 10],
['PENNY', 1],
['PENNY', 1],
['PENNY', 1],
['PENNY', 1]];

const b = arr.reduce((a,c) => {
    if (a.has(c[0])) {
        a.get(c[0])[1]+=c[1];
    } else {
        a.set(c[0],c);
    }
    return a;
},new Map());
console.log(b);

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

Innovative JavaScript function

Seeking a solution for my JavaScript function that should only be executed when the browser screen width exceeds 1024px. if ($(window).width() > 1024) { An issue arises when a user initially loads the webpage on an 800px browser screen and then resize ...

Determine the shared elements between two distinct arrays and create an object that includes these common elements

I am dealing with 2 different arrays of objects var array1 = [ {id: 1, name:'fruit', rating:5}, {id: 4, name:'vegetable', rating: 3}, {id: 8, name:'meat', rating:1} ]; var array2 = [ {alimentId: 1, quantity: 2}, {alimentId: 4 ...

Is it valid JSON to have values such as "ok", false, true, null, and 123?

Can the following strings be considered valid JSON? "ok" false true null 123 If not, why does the standard JavaScript JSON.parse method allow these values to be used as valid JSON? I have encountered issues when using these values in JSON REST APIs, ...

Unlocking the secret dropdown menu with Java Selenium WebDriver

Is there a way to retrieve a hidden dropdown menu on a webpage using selenium webdriver? The process involves selecting an option from a navigation bar, which triggers the appearance of the dropdown menu. I then need to choose a value from the list on the ...

Issue: The variable THREE has not been defined within the FBXLoader code

Currently, I am utilizing the module version of three.js in order to execute imports from a client-side JavaScript file structure. The core functionality of THREE is working correctly. However, I am encountering an issue when attempting to use it with FBX ...

Having difficulty in displaying database values in HTML modal using PHP

On my PHP page, I have a setup that displays data based on the fetched id from the URL. Everything is working smoothly, but when I click a button to show a modal with additional information, the modal appears blank. Here is the code snippet I am using: ...

Perform an ajax request to check for the existence of an image and insert

I've been trying to implement asynchronous JavaScript based on guidance from this answer, but I'm facing some difficulties in understanding where things are going wrong. My goal is to use autocomplete functionality to request specific files from ...

Enabling automatic scaling during the rendering of an .stl file using three.js

I'm in the process of developing a server/webpage with the following functionality: Users can upload an .stl file to be 3D-printed The server executes a mesh repair script on the uploaded .stl file The corrected .stl file is displayed in the user&ap ...

Use PHP regular expressions to search through arrays and calculate the sum of the last numbers

Recently, I received a file with a structure similar to this: 12345 ABC 100M 001 2.0 ABC 1010 4510 A01 451 Apple, Johnny A 150 12345 ABC 100M 011 2.0 ABC 1010 4510 A01 451 Apple, Johnny A 80 12345 ABC 100 011 2.0 ABC ...

Tips for deciphering the encoded array value

Looking to parse the array value within a web service. Specifically, I need to extract the data from the 'CONTENT_VALUES' field, which contains objects with name and value attributes. Once parsed, the extracted values should be assigned to json.I ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

Change the image size as you scroll through the window

While my opacity style is triggered when the page is scrolled down, I am facing an issue with my transform scale not working as expected. Any suggestions on how to troubleshoot this or any missing pieces in my code? Codepen: https://codepen.io/anon/pen/wy ...

Having trouble implementing uppercase text in Bootstrap editable modules

Recently, I implemented the bootstrap editable function in my application and it was functioning perfectly. However, I am now looking to have the editable text always display in uppercase format. Unfortunately, I am unsure of how to achieve this. Any sugge ...

When using json_decode with $_POST, it may return NULL

Having difficulty with json_decode and a valid JSON being sent via $_POST. Here's the JSON object, stored in the "inventory" variable: [{"item_name":"Screw Driver","item_desc":"asdasd","item_type":"weapon"}, {"item_name":"Brown Shoes","item_desc": ...

Ensure that the value is updated upon clicking on the radio buttons and store the value in a session variable for

I'm working on a feature that involves two radio buttons: one for shipped and the other for not shipped. The requirement is that when the first radio button is clicked, an amount of 100 should be added to the total price. If the second radio button is ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

Observing attribute changes in AngularJS directives

How can AngularJS observe attributes on a custom directive to bind Angular values? Here is my current progress: <tile title="Sleep Duration" data-value="{{sleepHistory.averageSleepTime}}"/> app.directive('tile', [function() { return ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...

Checking TinyMCE to ensure it handles empty inputs properly

I find TinyMCE to be a highly effective WYSIWYG editor. The editor functions well, but I encounter an issue when trying to check if it is empty. Challenge I am in need of validating the content input in the TinyMCE textarea to ensure that something ha ...

Engaging three-dimensional design inspired by JavaScript frameworks

I'm interested in developing an interactive 3D application using JavaScript. I'm curious to know if either babylon.js or three.js have support for interactivity. I've searched for information on this but haven't found much, and the docu ...