Performing additions on two-dimensional arrays using Angular/JavaScript

Currently, I am in the process of learning basic JavaScript and could use some assistance. My task involves working with two-dimensional arrays where the 0th index will always represent a date and the 1st index will always be an integer in the array. My goal is to create a new array consisting of unique objects with types A and B by summing up the values at the 1st index of each two-dimensional array. See the example code below:

 $scope.mainArray = [{
    type: 'A',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'B',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'A',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, {
    type: 'B',
    values: [
      [111111, 12],
      [111111, 12],
      [111111, 11],
      [111111, 2],
    ]
  }, ];

Should convert to

  $scope.newArray = [{
    type:'A',
    values:[
      [11111,24],
      [11111,24],
      [11111,22],
      [11111,4],
      ]
  },{
    type:'B',
    values:[
      [11111,24],
      [11111,24],
      [11111,22],
      [11111,4],
      ]
  }];

Here is the Plunker link for reference.

I would greatly appreciate any assistance provided. Thank you!

Answer №1

After reviewing the updated snippet, I have provided a sample implementation using map, filter, and reduce to achieve the desired output.

  $scope.typeAArray = $scope.mainArray.filter(function (item) {
    return item.category === 'A';
  }).reduce(function (accumulator, current) {
    var newObject = {
      category: accumulator.category,
      values: []
    };
    
    accumulator.values.map(function (val, index) {
      newObject.values.push(val);
      newObject.values[index][1] += current.values[index][1];
    });
    
    return newObject;
  });

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

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

What is the total amount within a specified date range when retrieved as JSON?

Consider the following JSON structure: { "timesheets": [ { "user": { "username": "erik", "first_name": "Erik", }, &q ...

The pop-up fails to appear

Could you assist me in identifying the issue with my code? <script type="text/javascript"> function PopupCenter(pageURL, title,w,h) { var left = (screen.width/2)-(w/2); var top = (screen.height/2)- ...

Node.js captures the Promise and provides detailed feedback

As I embark on my journey with Node.js + Express, currently in the process of structuring my HTTP APIs, I have a controller that utilizes a specific pattern: my_controller.js 'use strict'; var AppApiFactory = function (express, appService) { ...

Loading templates dynamically within ng-repeat is a powerful feature that enhances the flexibility and

I need help loading a template dynamically while using an ng-repeat: <ul> <li ng-repeat="prop in entity" > <div ng-include src="prop.template"></div> </li> </ul> The value of prop.template is the URL of ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Determining the decimal power using the position of a for-loop

After selecting a number, the task is to generate circles using d3.js. Each circle will be assigned a color from an array: var color =["red", "blue", "yellow", "orange",.....] ● For instance, if the user picks 593, the first 500 circles should be ...

The reset function in React Native Controller FormData TextInput does not work properly

Encountering an Issue: While on the sensor overview page, I select a specific sensor and proceed to edit its name. Upon saving the changes and navigating back to the list of all sensors, I notice that the updated name has been successfully modified. Howeve ...

Retrieve an element generated by a React script without using the ref attribute

There is a chat button on my website generated by a script (zendesk chat) that creates an iframe with the ID "launcher". I am using Nextjs and I am trying to access this element, but I am unable to attach a ref since I do not have the code. I have been sea ...

Struggles faced while trying to set up Karma using NPM

Attempting to set up Karma on a system running node v0.10.13 and npm 1.3.2. Tried both with and without sudo permissions. Here is the log: npm http GET https://registry.npmjs.org/karma ... (Error messages related to failed fetches from registry) ... > ...

Implement a feature in JS/HTML where clicking on a button shifts a specific section of a row from one table to another while simultaneously deleting the remaining

I am facing an issue with two tables - addFriends and existingFriends. The addFriends table contains a button in the fourth column, which, upon clicking, should delete the corresponding row from that table and add it to the existingFriends table. Currentl ...

Opening the Gmail app from a link using JavaScript

What is the best way to open the Gmail app from a hyperlink? This link opens WhatsApp <a href="https://wa.me/">whatsapp</a> <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f ...

What is the best way to transfer data between controllers in my particular situation?

Currently, I am working on developing a factory for the restful services. The main challenge I'm facing is how to transfer data from one controller to another in AngularJS. Specifically, I need to use the data obtained from the first service call to ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

Why isn't Latex rendering when called from Javascript?

Below is the code I'm working with: function test() { document.getElementById('demo').innerHTML="$$\left[ x=0 \right] $$";//same code from demo1.but not rendered } test(); <script type="text/javascript" src="http://latex.co ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

Leverage the JSON information retrieved from a WebApi to enhance functionality in an AngularJS

After making a request to a WebApi, I received JSON data as a response. However, when trying to access this data from angularJS, I encountered an issue. The structure of the data is as follows: { "$id": "1", "result": [ { "$id": "2", " ...

Attempting to develop a filtering feature using ReactJS

Having some trouble with the if statement in my filter list function. Can't seem to figure out why it's not working properly. Here is the code snippet: filterList (event) { var updatedList = this.props.array; var filterText = this.stat ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...