Is there a way to combine the elements of one array with their counterparts in multiple other arrays using JavaScript or Angular?

I am trying to combine the elements of multiple arrays in a specific order, similar to the question found at [How can I add each element of one array to another one's corresponding element using a ParallelStream?. However, my approach involves using javascript and angular. The arrays I am working with may contain up to 31 elements (days), but each data object will always have the same number of elements.

$scope.test31days = {
  "change_series": [
    { "data": [0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,2,0,0],
      "name": "EMERGENCY",
      "color": "#904040"},
    { "data": [0,1,3,0,0,0,0,1,2,3,3,0,0,0,2,1,1,1,0,0,1,1,3,3,1,0,0,1,2,2,0],
      "name": "MINOR",
      "color": "#333"},
    { "data": [0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0],
      "name": "MAJOR",
      "color": "#666"}
  ],
  "change_title": "CHANGES"
}

Upon inspecting the console output, it appears that I am correctly segregating the elements, albeit encountering issues when implementing the if/else if statement. This causes the browser to crash, indicating errors in my code structure.

$scope.getTotalChanges = function(){
  var series = $scope.test31days.change_series;
  var arry = [];

  for(var i = 0; i < series.length; i++){
    var seriesData = series[i].data;

    for(var j = 0; j < seriesData.length; j++){
      
      if (j === 0) {
        arry = seriesData;
      } else if (j > 0) {
        arry[j] += seriesData[j];
      }
    }
  }

  console.log('arry ', arry);
  return arry;
};

My objective is to compile a single array containing data for all 31 days.

Answer №1

let seriesData = $scope.test31days.change_series;
let dataListLength = seriesData[0].data.length;
let finalResult = Array.apply(null, new Array(dataListLength)).map(Number.prototype.valueOf, 0); //initialize final result array with zeros

for(let a = 0; a < seriesData.length; a++) {
  for(let b = 0; b < dataListLength; b++) {
    finalResult[b] += seriesData[a].data[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

Sending an array to a .NET web service from an iOS SDK

When developing my iPhone app, I enjoy using JSON web services. Here is how I attempt to pass an array: NSArray *keys = [NSArray arrayWithObjects:@"key",nil]; NSArray *objects = [NSArray arrayWithObjects:venueId,nil]; NSDictionary *jsonDictionary = [NSDi ...

Problem encountered in Typescript when using async/await with Promise.all to iterate through multiple results

Encountering an issue with this result set because its type is unknown. Despite trying various approaches, the same error persists and I'm uncertain about the next steps to take. Any assistance would be greatly appreciated! Here's the specific e ...

Endless recursive function loop

I am working on a solution to iterate over a 2D array and create subarrays whenever a different value is found in a specified column. For example: TEST <----- This value should be ignored. Start counting at index 1. A A A -------- split here -------- B ...

Displaying a ReactJS component inside a map function by giving it a unique identifier

When I click on a button within a .map function, I want only the component I clicked on to be displayed and not repeated in all the others. Currently, the behavior of the component is as follows. https://i.sstatic.net/FxsGC.png Clicking on the three dots ...

Order a array of JSON by time, showing it in a 12-hour format

I've come across a JSON structure that looks like this: [ { "Event_code": "AB-001", "Start_time": "11:00 AM", "End_time": "3:00 PM", "Session_type": "Tour" }, { "Event_code": "AB-002", "Start_time": "09:30 AM", "End_ ...

Loop through a PHP array containing a mix of different data types

I am having trouble with the formatting of my array output. Array: Array ( [0] => Photography & Video:Online Video [1] => Photography & Video:Digital Files [2] => Shooting Types:Ring Shots [3] => Shooting Types:Wedding Shots ) Output: (Using ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

Whenever I attempt to retrieve JSON data, I keep receiving an [object object] alert

When I try to retrieve JSON data from an online server instead of localhost, I'm encountering an [object object] alert. The code works perfectly on localhost. Here is the ASPX code: $(document).ready(function () { $('#btnGetEmployee&a ...

Three JS does not support dynamic color changing functionality

In my ThreeJS project, I have created a 3D wall and am attempting to change its color dynamically on a click event. However, the code doesn't seem to be working as expected. Can you help me identify the error in the following code snippet? var materi ...

What is the best way to incorporate sorting functionality into my CRUD table?

Below is the backend code snippet: app.get("/sortedcustomers", (req, res) => { db.query("SELECT * FROM customer_info ORDER BY contacted", (err, result) => { if (err) { console.log(err); } else { res.send(result); } }); }); ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

When retrieving data from Select2, a string is being returned instead of an

I am facing a challenge with multiple <select class="searchselect"> elements in my HTML, each filled with numeric values. To initialize Select2, I am utilizing the code snippet below: $(".searchselect").select2({ ajax: { dataType ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

Ensure that the width of the table rows (tr) matches the width of the table header

I'm currently working on implementing a sticky table header. The issue I'm facing is that the width of tableHeaderRow does not match the width of tableHeader. Steps taken for creating sticky header: Make an Ajax call to populate the table with ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

Incorporate a NodeJS express object into AngularJS 1.6

I am currently facing a challenge with passing parameters from a NodeJS API to AngularJS so that I can retrieve data for a specific page. My situation is an extension of the issue discussed in this question: How do I pass node.js server variables into my a ...

Performing double string splitting with multiple separators in javascript

If I have a string like a.b.c.d#.e.f.g.h#.i.j.k.l and want to split it first by "#" and then by ".": str = a.b.c.d#.e.f.g.h#.i.j.k.l res = str.split("#") res[0] will contain a.b.c.d after the first split. Now, I need to further split this data. Is th ...

A potential memory leak occurs in Nuxt on the client side when dynamically loading a component

I'm currently working on a NuxtJS application where I need to dynamically load components. While my code successfully loads the component on the server-side, the browser seems to encounter a significant memory leak during page loading, making it impos ...

Guide to creating a reminder feature in NestJS

In my NestJS project, I've created a POST API to add a Date object representing the date and time for sending notifications to a mobile app. Currently, I am working on checking which reminders have been reached for all users in order to trigger remin ...

What are the disadvantages of using getBoundingClientRect() in ReactJS?

I recently incorporated the getBoundingClientRect() method into my project. However, a fellow React developer expressed concerns about its browser compatibility. In theory, shouldn't Webpack or Babel handle such compatibility issues? ...