简体   繁体   中英

Identify arrays with same first element and sum other elements based on index

Hi Javascript Experts,

I have an array as below

[["Database_Config",   19, 0,  0, 0, 0,  0]
["Database_Config",   0,  26, 0, 0, 0,  0]
["apiDomainListener", 0,  0,  1, 0, 0,  0]
["apiDomainListener", 0,  0,  0, 1, 0,  0]
["Database_Config",   0,  0,  0, 0, 27, 0]
["Some_other_Config", 0,  4,  0, 0, 3,  0]]

requirement: (if two arrays with a same first element found.. just need to sum the other elements of both arrays based on the index and maintaining order of elements)

please suggest the best way to do this? (vanilla javascript or jquery) order of elements is important

output expected as below

[["Database_Config",  19, 26, 0, 0, 27, 0]
["apiDomainListener", 0,  0,  1, 1, 0,  0]
["Some_other_Config", 0,  4,  0, 0, 3,  0]]

You could take the first item as key and search in the result set for a same group. Then update the values.

 var data = [["Database_Config", 19, 0, 0, 0, 0, 0], ["Database_Config", 0, 26, 0, 0, 0, 0], ["apiDomainListener", 0, 0, 1, 0, 0, 0], ["apiDomainListener", 0, 0, 0, 1, 0, 0], ["Database_Config", 0, 0, 0, 0, 27, 0], ["Some_other_Config", 0, 4, 0, 0, 3, 0]], grouped = data.reduce((r, [key, ...values]) => { var temp = r.find(([q]) => q === key); if (temp) values.forEach((v, i) => temp[i + 1] += v); else r.push([key, ...values]); return r; }, []); console.log(grouped);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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