Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays:

barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Phone"]

barData.datasets[0].data["2", "8", "20", "200", "1", "300", "400", "500", "77", "7", "99"]

My goal is to identify duplicate values in barData.labels, then sum up the corresponding values in barData.datasets[0].data and remove the duplicates. For instance, if there are 2 entries for 'Food', I want to combine and delete one entry.

Is there a way to achieve this?

Answer №1

Consider using a JavaScript object instead of utilizing two arrays in this scenario. It may be more efficient to do so at the time of creation.

An example implementation could look like this:

barData = {
  "Food": ["12", "6", "15", "100", "3", ...]
}

With this structure, if you need to add another Food category, you can easily verify whether it already exists within the barData object. If not, you can create it; otherwise, you simply append an element to the existing array for that specific Food key.

Answer №3

By utilizing a map to keep track of duplicates, you can effectively determine when to add values and where to calculate sums.

Consider the following approach:

let ls = [ ... ];
let vs = [ ... ];
let dups = {};
let lls = [];
let vvs = [];
for(let i = 0, len = vs.length; i < len; i++) {
    let l = ls[i]; 
    let v = vs[i];
    if(dups.hasOwnProperty(l)) {
        let ii = dups[l];
        vvs += vs[ii];
    } else {
        let ii = vvs.length;
        dups[l] = ii;
        lls[ii] = l;
        vvs[ii] = v;
    }
}

Answer №4

Imagine you have two arrays set up like this:

var categories = ["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Phone", "Phone", "Status", "Status"];
var dataValues = ["2", "8", "20", "200", "1", "300", "400", "500", "77", "7", "99", "1", "333", '77'];

Now your goal is to get an output similar to this:

var finalResult = {
  "Food": ["2","8","20","200","1","300","400","500","77","7"],
  "Phone": ["99","1"],
  "Status": ["333","77"]
}

The following code snippet accomplishes that:

var tempArr = []
var finalResult  = {};
for(index in categories){
   var category = categories[index];
   if(tempArr.indexOf(category) > -1){
      finalResult[category].push(dataValues[index])
   }
   else{
      tempArr.push(category);
      finalResult[category] = [dataValues[index]];
   }
}
console.log(finalResult);

If you want to sum the values, you can modify the code slightly like so:

var tempArr = []
var finalResult  = {};
for(index in categories){
   var category = categories[index];
   if(tempArr.indexOf(category) > -1){
      finalResult[category]= parseInt(dataValues[index]) + parseInt(finalResult[category]);
   }
   else{
      tempArr.push(category);
      finalResult[category] = dataValues[index];
   }
}
console.log(finalResult);

Answer №5

If you want to consolidate your values and convert them back into the original array format, one approach is to store the values in a temporary object, summing them up as you iterate through the array. Then, you can rearrange the values to match the structure of the original array.

// Original array creation
var barData = {};
barData.labels = ["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Phone"];
barData.datasets = [];
barData.datasets[0] = {};
barData.datasets[0].data = ["2", "8", "20", "200", "1", "300", "400", "500", "77", "7", "99"];
// Displaying original object
$("#original").text(JSON.stringify(barData));
var newBarData = {};
for (var i = 0; i < barData.labels.length; i++) {
  if (newBarData[barData.labels[i]] === undefined) {
    newBarData[barData.labels[i]] = {};
    newBarData[barData.labels[i]].labels = barData.labels[i];
    newBarData[barData.labels[i]].value = parseInt(barData.datasets[0].data[i]);
  } else
    newBarData[barData.labels[i]].value += parseInt(barData.datasets[0].data[i]);
}

// Convert back to original format
barData = {};
barData.labels = [];
barData.datasets = [];
barData.datasets[0] = {};
barData.datasets[0].data = [];
$.each(newBarData, function(index, me) {
  barData.labels.push(me.labels);
  barData.datasets[0].data.push(me.value);
});

$("#result").text(JSON.stringify(barData));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="original"></div>
<div id="result"></div>

Answer №6

To enhance efficiency, my recommendation is to construct an object that encapsulates the distribution of the items, followed by a recreation of the labels and counts.

var labels = ["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Phone"],
    data = ["2", "8", "20", "200", "1", "300", "400", "500", "77", "7", "99"],
    distribution = labels.reduce(function (r, a, i) {
        r[a] = (r[a] || 0) + +data[i];
        return r;
    }, {});

Object.keys(distribution).forEach(function (k, i) {
    if (!i) {
        labels = [];
        data = [];
    }
    labels.push(k);
    data.push(distribution[k]);
});

document.write('<pre>' + JSON.stringify(labels, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

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 Javascript to access a website from a Windows Store application

Currently, I am working on a project to create a Windows store app using HTML and JavaScript. One of the key components of my app involves logging into a specific website with a username and password. Here is an example website for reference: The process ...

Setting an HTML element ID on a material-ui component: A step-by-step guide

I have a website that was created using Gatsby.js and incorporates the Material-UI framework. The specific issue at hand is as follows: I am looking to implement Google Tag Manager "Element Visibility" triggers. The goal is for GTM to trigger a Google Ana ...

Design an interactive div element that allows users to modify its content, by placing a span

Here is an example of the desired effect: ICON LINE - 1 This is some sample text inside a div element and the next line should begin here ICON LINE - 2 This is some sample text inside a div element a ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

Improve the translation animation on an element containing numerous child nodes

Looking for ways to enhance the smoothness of the transition in the "infinity list" animation. While it's just a demo at the moment, the real app will have various elements emerging from each "pin". The main performance bottleneck seems to stem from t ...

Tips for properly formatting the sort_by parameter in Cloudinary to avoid errors

Greetings to the helpful stack overflow community, I have encountered an issue with fetching images from cloudinary via a post request. Everything works fine until I include the sort_by parameter in the URL. This results in an error related to the format ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...

Is there a way to dynamically refresh the options in a select dropdown using jQuery?

I'm facing an issue with updating the options in a select element. Here is how my current select element looks: <select id="productId"> </select> Below is the jQuery code I am using: ... if (data.success) { var items = []; $.ea ...

Creating Seamless, Unified Shape-to-Shape (Containers) Transition with CSS and JavaScript - A Step-by-Step Guide

I am experimenting with creating a unique effect where two rectangular shapes, each containing text and with rounded ends, move towards each other, merge to form a single rounded rectangle as the page is scrolled down, and then separate back when scrolling ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

Is there a way to streamline the import process for material-ui components?

Is there a shortcut to condense all these imports into one line? As a newcomer to react, I've noticed that every component must be individually imported, especially when it comes to CSS components. Could you provide me with a suggestion on how to st ...

I found myself pondering the significance of the {blogs: blogs} in my code

app.get("/articles", function(req, res){ Article.find({}, function(err, articles){ if(err){ console.log("an error occurred!!!"); }else{ res.render("homepage", `{articles: articles}`); } }); I created this c ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Sliding with JavaScript

I'm looking to develop a unique web interface where users can divide a "timeline" into multiple segments. Start|-----------------------------|End ^flag one ^flag two Users should be able to add customizable flags and adjust their position ...

Node.js has the ability to establish internal connections, however it cannot establish connections

I'm having an issue connecting to a JavaScript file on my local server. I'd like to input the external IP address and port in order for it to run externally. This functionality currently works when accessed locally. Below is the code from my serv ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...