Adding up the elements of an array that match with elements in another array

In my JavaScript code, I am facing a challenge that I have been struggling to solve. I have attempted various methods, but none have proven successful for me so far. The situation is as follows: I have two arrays of equal length. For example:

var years = [2010, 2011, 2009, 2008, 2010, 2011, 2007, 2008, 2008];
var money = [2, 3, 6, 5, 13, 8, 3, 9, 7];

Each element in the money array corresponds to an element at the same index in the years array, representing funds spent in that year. My goal is to create a new array of distinct years (removing duplicate values from the original years array) and a new money array with elements that are sums of the initial money values associated with each year.

years_new = [2010, 2011, 2009, 2008, 2007];
money_new = [2 + 13, 3 + 8, 6, 5 + 9 + 7, 3];

I'm looking for guidance on how to achieve this task efficiently. Any help would be greatly appreciated. Thank you!

Answer №1

To create an object, you can employ the Array.prototype.reduce method. This will result in keys representing years and their corresponding values being the sum of the elements in the money array.

var newObj = years.reduce(function(obj, year, index) {
    obj[year] = (obj[year] || 0) + money[index];
    return obj;
}, {});

To obtain all the years, the Object.keys method can be utilized:

var newYears = Object.keys(newObj);
var newMoney = newYears.map(function(year) { return newObj[year] });

Answer №2

Here is an alternative method that utilizes the following helper functions (please note that any other similar uniq function can be used, as efficiency is not the primary focus here).

Helpers.

Array.prototype.uniq = function() {
  return this.reduce(function(result, current) {
    return result.indexOf(current) < 0 ? result.concat([current]) : result;
  }, []);
};

Array.prototype.indicesOf = function(element) {
  return this.reduce(function(indicesArray, currentItem, index) {
    return (currentItem === element) ? indicesArray.concat(index) : indicesArray;
  }, []);
};

Usage.

Now to select the unique years, all you need to do is call uniq:

var new_years = years.uniq();

To map the old money to the corresponding new ones, we iterate through each new year and sum up the money values based on their indices in the original array:

var new_money = new_years.map(function(new_year) {
  return years.indicesOf(new_year).reduce(function(total, ind) {
    return total + money[ind];
  }, 0);
});

Answer №3

Here is a potential solution:

let years = [2010, 2011, 2009, 2008, 2010, 2011, 2007, 2008, 2008];
let money = [2, 3, 6, 5, 13, 8, 3, 9, 7];

const fixed_years = {};

for(let i = 0; i < years.length; i++) {
    if(fixed_years[years[i]]) {
        fixed_years[years[i]] += money[i]; 
    } else {
        fixed_years[years[i]] = money[i];
    }
}

console.log(fixed_years);

const new_years = Object.keys(fixed_years);
const new_money = Object.values(fixed_years);

console.log(new_money);

Answer №4

To keep track of counted values, consider using a temporary object.

var years = [2010, 2011, 2009, 2008, 2010, 2011, 2007, 2008, 2008],
    money = [2, 3, 6, 5, 13, 8, 3, 9, 7],
    count = {}, i = 0,
    years_new = [],
    money_new = [];

while (i < years.length && i < money.length) {
    count[years[i]] = (count[years[i]] || 0) + money[i];
    i++;
}
years_new = Object.keys(count);
money_new = years_new.map(function (a) { return count[a]; });

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

If you prefer to count without any temporary storage, another method maintains the order of the original years array.

var years = [2010, 2011, 2009, 2008, 2010, 2011, 2007, 2008, 2008],
    money = [2, 3, 6, 5, 13, 8, 3, 9, 7],
    i = 0, p,
    years_new = [],
    money_new = [];

while (i < years.length && i < money.length) {
    p = years_new.indexOf(years[i]);
    if (~p) {
        money_new[p] += money[i];
    } else {
        years_new.push(years[i]);
        money_new.push(money[i]);
    }
    i++;
}
document.write('<pre>' + JSON.stringify(years_new, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(money_new, 0, 4) + '</pre>');

A different approach involves reducing both arrays by comparing indexes of years and utilizing Array.prototype.indexOf. This method splices both arrays and incorporates the spliced value accordingly.

var years = [2010, 2011, 2009, 2008, 2010, 2011, 2007, 2008, 2008],
    money = [2, 3, 6, 5, 13, 8, 3, 9, 7],
    i = years.length, p,
    years_new = years,
    money_new = money;

while (i--) {
    p = years_new.indexOf(years_new[i]);
    if (p !== i) {
        years_new.splice(i, 1);
        money_new[p] += +money_new.splice(i, 1);
    }
}
document.write('<pre>' + JSON.stringify(years_new, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(money_new, 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 the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

Mastering the art of targeting table row elements in Shiny using Javascript

I'm currently developing a shiny app that incorporates a gt table. I want to make the text bold in the .gt_group_heading class if it's capitalized. It appears that any text passed to this element is treated as plain text within the td tag and ...

Closing notifications in Bootstrap 5.1 with the help of Ajax

I am utilizing bootstrap 5.1 alerts to display custom messages after an Ajax call. I also want the ability to dismiss the alert as necessary, which can be done with a dismiss button provided by bootstrap. Below is the PHP code I am using : <div class=& ...

Ensure that multiple URLs within an object are properly sanitized instead of just focusing on a single

I am working with an object that contains success, summary, and detail elements, which are used to display messages in PrimeNG message component (p-messages) after a record is created. Once the record is created, I invoke the displayMessage method to set t ...

The NativeAppEventEmitter does not return any value

I've been grappling with obtaining a logged in user access token for quite some time. I initially faced challenges with it in JavaScript, so I switched to Objective-C and managed to succeed. Following that, I referred to this RN guide: https://facebo ...

I want to transfer specific rows from one table to another HTML table, and I'm looking to do it using either JQuery

I have some data in a source table that I need to copy and append to a destination table with the click of a specific row button. The total price from the price column of the destination table should be displayed within an h1 tag. Additionally, there sho ...

Missing RequestVerificationToken value when hiding HTML element using jQuery

I am encountering an issue with my ASP.NET MVC 4 form that involves checkboxes being used to show and hide certain HTML elements. When I initially visit the form page, the RequestVerificationToken value is correctly created as a hidden field. Some HTML ele ...

Creating a text box that displays an inverted input

Hello, I'm looking to create a text box where if I input 1 then 2, it will display 21. Then if I enter 3, it should show 321. I am currently using Vue.js on my front end. Here is what I have attempted so far: I experimented with methods such as watc ...

Is it necessary to establish integer variables to keep count while invoking a method?

Here is the scenario: Create a method called occursMoreTimes that determines if the number of occurrences of val1 in an array is greater than the number of occurrences of val2. You can choose to use the findNumberOf method if you see fit. /** *Returns t ...

Divide the string in clojure and finally display it

I've recently started learning about clo​j​ure. My goal is to split a String and then display the result. If I use the following code : (.split "Dasher Dancer Prancer" " ") The output is #<String[] [Ljava.lang.String;@64e0e8ca>, which repr ...

Waiting for user submission before executing a JavaScript function

const onSubmit = ()=>{ someFunction().then(()=>{ // next step is to wait for user interaction by clicking a specific button // user initiates the action // perform specific task }) } Essentially, after the initial form submissi ...

Apollo Client's useQuery function is causing unnecessary refetches when using Next.js' router.push method

Currently, I'm facing an issue where a query within a useQuery Apollo Client hook is being re-run unnecessarily every time Next.js's router.push function is triggered. The problem code snippet looks like this: const Parent = () => { useQuery ...

If the error state is true, MuiPhoneNumber component in react library will disable typing, preventing users from input

I am currently trying to implement the material-ui-phone-number plugin for react, using Material UI. Whenever the onChange event is triggered, it calls the handlePhone function which stores the input value in the state. However, I have encountered an issue ...

I'm interested in developing a React function that generates recipe components based on a set of instructions provided in an array, along with a separate parameter specifying the recipe name

I am currently immersed in the book "Learning React" written by O'Reilly. The book mentions a method of creating components by using a function known as the "component creating function". It advises supplying the necessary parameters as the second par ...

Error message: "Unable to locate jQuery file within the node.js + Express application running on Heroku platform."

My current setup involves a node.js application with Express and express-handlebars deployed on Heroku. However, whenever I run the app, the console displays a 404 error for the jquery file, leading to subsequent failures for dependent libraries like Boots ...

Issue with parsing JSON values in a Chrome extension

Struggling to retrieve the value of a JSON key, but it keeps returning empty. Check out the code snippet below: let json_=JSON.parse(JSON.stringify(result)); console.log(json_); console.log(json ...

Efficiently saving multiple objects at once: updating and creating with hierarchical relationships

I am facing an issue with creating objects from JSON while simultaneously validating it. My goal is to avoid inserting or updating these objects in the database if the JSON format is incorrect or contains unacceptable numbers (in arrays). Instead, I want t ...

My application built with React and Flask successfully processes JSON data on one route, but encounters issues on another route

The code I have in place is working quite well, with the frontend being the next area of focus. This code effectively registers a user and updates the database: export default class APIService { static RegisterUser(username, email, password, base_city, ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Utilize String to Set Cookies

My goal is to utilize requestjs for making requests and sharing cookies across various JavaScript files and servers. To achieve this, I have chosen to store the cookies in a database as a string and retrieve them when necessary. The string format aligns w ...