Comparing ID numbers and adding them together before storing them in a new array

In order to consolidate numbers with the same sequence ID and store the total sum in a new array named 'final', follow the steps below:

INPUT =>

$scope.initial = [{seq:11, name:'ABC', number:20},
                  {seq:11, name:'ABC', number:50},
                  {seq:11, name:'ABC', number:80},
                  {seq:12, name:'DEF', number:30},
                  {seq:13, name:'JKL', number:10},
                  {seq:13, name:'JKL', number:15}];

OUTPUT =>

$scope.final = [{seq:11, name:'ABC', number:150},
                 {seq:12, name:'DEF', number:30},
                 {seq:13, name:'JKL', number:25}];

Appreciate your cooperation!

Answer №1

 $scope.newArr = [];
 var accumulator = {};

 for(const {index, title, value} of $scope.initialArray){

   if(index === accumulator.index && title === accumulator.title){
     accumulator.value += value;
   } else {
     $scope.newArr.push(accumulator = {index, title, value});
   }

 }

An efficient way to combine elements based on certain conditions is to use an accumulator. It helps keep track of the current resulting element being built. By checking if the current element matches the accumulator, the values can be aggregated accordingly or a new element can be added as the new accumulator.

Answer №2

Iterate through the array and verify if the specified sequence exists, if not, then append it

var data = [{
    seq: 11,
    name: 'ABC',
    number: 20
  },
  {
    seq: 11,
    name: 'ABC',
    number: 50
  },
  {
    seq: 11,
    name: 'ABC',
    number: 80
  },
  {
    seq: 12,
    name: 'DEF',
    number: 30
  },
  {
    seq: 13,
    name: 'JKL',
    number: 10
  },
  {
    seq: 13,
    name: 'JKL',
    number: 15
  }
];
var groupedData = [];
data.forEach(function(entry) {
  if (!this[entry.seq]) {
    this[entry.seq] = {
      seq: entry.seq,
      name: entry.name,
      number: 0
    };
    groupedData.push(this[entry.seq]);
  }
  this[entry.seq].number = (+this[entry.seq].number + +entry.number);
}, Object.create(null));

console.log(groupedData);

Answer №3

If you want to simplify your code, consider using the reduce method like this:

$scope.data = [
    {id:1, name:'John', age:25},
    {id:2, name:'Jane', age:30},
    {id:3, name:'Alice', age:35},
    {id:4, name:'Bob', age:40}
];

var reducedData = $scope.data.reduce(function(acc, curr){
    acc[curr.id] ? acc[curr.id].age += curr.age : acc[curr.id] = curr;
    return acc;
}, {});

$scope.result = Object.keys(reducedData).map(function(key){ return reducedData[key]; });

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

Trouble with CSS and JS tabs not activating when clicked?

I am experiencing issues with a navigation (organized in tabs) that is not functioning on this page, but it works correctly on this page using the same method for inclusion. When clicking "Norway" on the top left, the navigation opens but switching to the ...

Decoding the information received from Socket.IO within the Flash client

When utilizing server node.js and module Socket.IO, data transmission is handled as shown below: var tests = [555, 777]; client.send("Test string"); //first message client.send({tests:tests}); //second message If the data sent is a text string (fi ...

I'm still searching for a proper solution on how to access JavaScript/jQuery functions within Colorbox

For my website, I am utilizing PHP, jQuery/JavaScript, Colorbox (a jQuery lightbox plugin), Smarty, and other tools. Currently, I am working on displaying data in a popup using the Colorbox plugin. However, I am facing an issue with calling a JavaScript fu ...

An easy way to divide an array into a table

I've obtained these arrays from a JSON file "Works": [ {"TypeOfWork": "scaffolding", "Status": "done"}, {"TypeOfWork": "painting", "Status": "on-going"} ] My go ...

Retrieving JSON database entries from MySQL using PHP

I'm currently working on an app with a challenging client who often changes their requirements. To handle this, I've decided to store some data as JSON objects. Within the app, I have a system for matching users and storing their information as ...

How can you write a parameterless function in Ramda using a point-free style?

Take a look at this functioning code snippet: var randNum = x => () => Math.floor(x*Math.random()); var random10 = randNum(10) times(random10, 10) // => [6, 3, 7, 0, 9, 1, 7, 2, 6, 0] The function randNum creates a random number generator that wi ...

Using Jquery to retrieve the window size and dynamically apply it to a div's CSS, adjusting it accordingly when the

Hey there! I'm trying to create a full-screen div, but unfortunately CSS doesn't seem to do the trick in this case. JavaScript/jQuery is my only option. My plan is to dynamically set the size of the div based on the browser window's dimensi ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

What are some ways to ensure that text can adapt to the size of a

I am looking to create dynamic text that adjusts based on the size of its parent container. As the parent container's size changes, I want the text to automatically adjust accordingly. Specifically, I want the text in a widget to resize when the widg ...

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...

Ajax failing to trigger upon submission

I need assistance in creating a form that will first submit via AJAX before directing to a specified URL. Once submitted, an email should be sent to me through newsletter.php <script type='text/javascript'> $(function () { $("#signup") ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...

Trouble resolving a timer interruption in JavaScript

Creating dynamic elements using PHP has brought me to a new challenge. I want to implement a functionality where the user can hover over an icon and see the related element, which should disappear after some time if the mouse leaves the icon. Additionally, ...

import the JSONP file from the local directory and assign it to a variable on

My current setup involves a local webpage that is loading a large JSON database file by utilizing a file named data.jsonp that contains data={a JSON dictionary of information}. I then import this file in my HTML using <script src="data.jsonp"& ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

Tips for triggering a method in the parent controller from a button inside a ui-grid enclosed within a custom directive

[summary] How can a button within a column template trigger a method in the surrounding controller when the grid is enclosed in a custom directive? [thanks] Let me illustrate using 3 plunkrs: P1) Implementing a basic action column in ui-grid http://pln ...

What is the process of converting exactPageList from any to any[] before assigning it to pagefield?

Encountering an issue with paging on my angular 7 app where I am unable to assign exactpagelist of any type to pagefield of type array. The problem seems to be occurring on the last line of the function totalNoOfPages at this point: this.pageField = this ...

Adjust the size at the location of the cursor

I am having trouble understanding how to implement zoom based on mouse position using this example here: (https://stackblitz.com/edit/js-fxnmkm?file=index.js) let node, scale = 1, posX = 0, posY = 0, node = document.querySelector('.f ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...