简体   繁体   English

集群二 object arrays javascript

[英]Cluster two object arrays javascript

I have two arrays我有两个 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, febuary should sum all febuary values and january values as well and so on. id 喜欢对这些数据进行聚类/排序以使 2 个 arrays 显示月份和相应的总值,本质上,获取与 1 月对应的所有值,将它们和 output 相加到另一个数组,2 月应该将所有 2 月值和 1 月值相加以及等等。 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

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.一种方法是创建一个临时的普通 object,以月份名称为键,以及相应的 integer 最初设置为 0。然后将出现在第二个数组中的值添加到这些整数中,对应于月份。 Finally break down that object into its keys and values:最后将 object 分解为它的键和值:

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

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对于示例数据, nov应该是27而不是24因为总和32减去dec (即5 )是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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM