Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
Cluster two object arrays javascript

I have two arrays

array1 = ['jan', 'mar', 'dec', 'jan', 'sep', 'nov', 'mar'];
array2 = [3, 5, 5, 4, 5, 8, 2];

as seen, each month can appear more than once.

id like to cluster/sort this data to have 2 arrays that show month and corresponding total values, in essence, get all the values that correspond to January, sum them and output them to another array, February should sum all February values and January values as well and so on. as well as a forth array containing months, without repeats. something like

array3 = ['jan', 'mar', 'sep', 'nov', 'dec'];
array4 = [7, 14, 19, 24, 32]; //totals
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

One way is to create a temporary plain object, keyed by the month names, and a corresponding integer that initially is set to 0. Then add to those integers the values as they appear in the second array, corresponding to the month. Finally break down that object into its keys and values:

var array1=['jan','mar','dec','jan','sep','nov','mar'];
var array2=[3,5,5,4,5,8,2];

var temp = Object.fromEntries(array1.map(month => [month, 0]));
array1.forEach((month, i) => temp[month] += array2[i]);
array1 = Object.keys(temp);
array2 = Object.values(temp);

console.log(JSON.stringify(array1));
console.log(JSON.stringify(array2));

about 4 years ago · Juan Pablo Isaza Report

0

First you need an array of all the months, then loop through that array to get the sum that below that month.

For the example data, nov should be 27 instead of 24 since total sum 32 minus dec(which is 5) is 27

// month map
const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

const array1 = ['jan','mar','dec','jan','sep','nov','mar']
const array2 = [3,5,5,4,5,8,2];

const result = months.reduce((sums, curMonth, i) => {
  if(array1.includes(curMonth)) {
    sums[curMonth] = array2.reduce((acc, value, index) => acc + (months.indexOf(array1[index]) <= i && value), 0);
  }
  return sums;
}, {});

console.log(result);

// get desired two arrays according to the result
const array3 = Object.keys(result);
const array4 = Object.values(result);

console.log(array3);
console.log(array4);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!