Home > Back-end >  Cluster two object arrays javascript
Cluster two object arrays javascript

Time:12-09

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

CodePudding user response:

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));

CodePudding user response:

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);

  • Related