Summing up similar values of elements in an array (JavaScript) using Angular

My Current Tools

  • Angular 5
  • AngularFire5
  • Firebase & Firestore

My Goal

I aim to iterate through an array containing objects. If a specific value in one object matches the same value in another object, I want to add their corresponding values together.

For Example:

Starting Data:

mapData = [{"countryCode":"US", "clicks": 5}, {"countryCode":"CAN", "clicks": 9}, {"countryCode":"US", "clicks": 6}]

or

mapData = [["US", 5], ["CAN", 9], ["US", 6]]

Desired Output:

mapDataResults = {
    "US": {
        "usage": 11,
        "fillKey": "tens"
    },
    "CAN": {
        "usage": 9,
        "fillKey": "ones"
    },
}

Where I Need Assistance

I am unsure how to efficiently search and match object values within the array. Additionally, I need help reformatting the data from an array to JSON format. Lastly, I would like to add a new key "fillKey" based on the number of clicks (or usage) for each country, which I believe I can do once the other steps are resolved.

Answer №1

If your initial collection is an array containing other arrays:

let dataEntries = [["USA", 8], ["MEX", 12], ["CAN", 7]];

function getLeadingDigitName(number) {
    switch(Math.floor(number).toString().length) {
        case 1: return 'units';
        case 2: return 'tens';
    }
}

function combineAndOutput(arr) {
    let finalResult = {};
    for(let j=0;j<arr.length;j++) {
        let mainKey = arr[j][0];
        let mainVal = arr[j][1];
        if(finalResult[mainKey]) {//already exists, so update
            finalResult[mainKey].total += mainVal;
        }
        else {//doesn't exist yet, so add 
            finalResult[mainKey] = { total: mainVal };
        }
        finalResult[mainKey].category = getLeadingDigitName(finalResult[mainKey].total);
    }
    return finalResult;
}

combineAndOutput(dataEntries);

Answer №2

If you are familiar with using lodash library, you may find the following code snippet helpful:

data = [{"UK", 4}, {"AUS", 8},{"UK", 7}];

You can then use _.sumBy(data, 'UK') or _.sumBy(data, "AUS")

All that is required is to map the response to an object. The provided instructions outline how to calculate and add the sum if additional data related to "UK" or "AUS" exists within the data array.

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

What is the best way to dynamically update cells within an HTML table row when a single column is changed?

My webpage features an HTML table that is dynamically constructed. Within this table, I have made some of the cells editable, with one cell containing a calculated value based on two other cells in the same row. Here is a snippet of my table: <tr class ...

Adding a SpotLight to Camera in ThreeJS: A Step-by-Step Guide

Trying to add a flashlight effect using Three.js r105 I'm attempting to attach a SpotLight to the camera to achieve a "Flashlight" effect. However, once I connect the SpotLight to my Camera, the light seems to completely stop working. What could be t ...

Displaying empty values in the post via plupload data

I have encountered an issue where a JSON string that I am trying to post is not getting posted, despite being visible in an alert. The strange part is that when I manually create a JSONArray, it gets posted successfully. Below is the code snippet, I would ...

Include a description in the cell of the table

I am struggling with adding a small description below one of the columns in my three-column table. I have tried using Grid, but so far, nothing has worked for me. Can anyone provide assistance? To give you a better idea, I have highlighted the desired res ...

Nodemon causing crashes in basic HTML pages

Having trouble getting a basic index.html page to work with nodemon. index.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </hea ...

Is it truly possible to return a reactive variable that updates its value asynchronously?

While reviewing the code of a frontend project developed in Vue3, I came across a unique construction that I have not encountered before. This has led to some confusion as I try to grasp how it operates. The concept involves assigning the result of an asyn ...

The type entity i20.CdkScrollableModule cannot be resolved to symbol in the nx workspace

After extensively researching online, I still haven't found a solution to this particular issue. I've attempted various troubleshooting steps, including deleting node_modules and package-lock.json, updating dependencies, and running nx migrate. ...

Tips for addressing lag problems in my Three.js game as time progresses

My game in Three.js doesn't start off with any lag, but after a few minutes, the performance begins to slow down on computers running it. I've tried reviewing my code and checking my arrays, adjusting values to troubleshoot, but so far, nothing s ...

Tips for effectively utilizing v-if, v-else within a v-for loop in your Vuejs application

<template> <div> <div v-for="box in boxes" :key="box.id"> <BaseAccordian> <template v-slot:title>{{ box.name }}</template> <template v-slot:content> <div v-for="paint in pai ...

What is the best approach to choose the thead element from a dynamically created table?

My table in JavaScript/JQUERY is dynamically constructed. Once the table is created, I am attempting to target the thead element. Here is a snippet of my code: $(document).ready(function(){ buildTbl(); }); function buildTbl() { var tbl = '< ...

Tips for effectively utilizing node modules that have yet to be installed without encountering any errors

I am looking to create a setup script for my NodeJS application. The script will: Establish system roles for users Create a root category for posts Finally, create a system admin user for the initial login These details will be saved in a database. Ad ...

When the state changes in React, the useSelector hook does not provide real-time updates

Currently, I am in the process of implementing a search feature using React and Redux Thunk. The main requirement for this search functionality is to fetch data from an API by calling a thunk action and updating the state accordingly for display on the UI. ...

Creating random numbers in HTML using JavaScript

Currently, I am attempting to develop an HTML random number generator using JavaScript to produce a randomized number and then notify the user of the generated number. However, I consistently encounter an error when obtaining my number, which is different ...

Which symbol is preferable to use in JS imports for Vue.js/Nuxt.js - the @ symbol or the ~ symbol?

I am seeking guidance on a matter that I have not been able to find a clear answer to. Webapck typically uses the ~ symbol as an alias for the root directory. However, I have noticed that some developers use the @ symbol when importing modules using ES6 s ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...

Encountering some problems while trying to use {return this.getAll.get(this.url)} to consume an API within Angular

I am currently delving into the world of Angular and Typescript to interact with APIs. While I have some experience working with APIs in Javascript, I am relatively new to this setup. The issue I am facing revolves around the code snippet below: To tackle ...

The GetStaticProps function in Nextjs is failing to load properly and is not passing the props data to

I am encountering an issue where I am unable to call the getStaticProps function in my Next.js/React project. My objective is to trigger the loading of getStaticProps when the page path transitions to /blog within my pages/blogs file. type BlogStaticInputs ...

Leveraging flot in conjunction with NPM, React, and Node

I've been attempting to utilize flot in a Node.js React project, but I'm running into issues with the import. The browser console is showing the error: Uncaught TypeError: _jquery2.default.plot is not a function This error is essentially the sa ...

Incorporate animated SVG directly into Vue templates without using any additional enclosures

I need to incorporate dynamic SVG code into my <template> without using v-html or any wrapper around it. The desired end result should look like the following, but template does not support v-html to achieve this. If there is a way to accomplish thi ...

Detect a modification event on a field lacking an ID using jQuery

I'm currently facing some challenges with jQuery and I really need to overcome them in order to complete the code I'm working on. The issue is that I can control the img tag, but unfortunately, I am unable to assign an ID to the input tag as des ...