Reputation: 33
I have a lot of arrays. I can list them together with for loops, however I need to show each element only one time if there are same elements in these different arrays. For example;
var array01 = [["Jack","92"],["Tom","74"],["Lily","100"],["Jonah","62"],["Lucy","83"]];
var array02 = [["Tom","94"],["Emma","70"],["Jack","100"],["Arnold","91"],["Kate","53"]];
var array03 = [["Jack","72"],["Tom","84"],["Emma","91"],["Jonah","92"],["Lucy","63"]];
var array04 = [["Emma","88"],["Marshall","82"],["Arnold","68"],["Ted","62"],["Lily","73"]];
var array05 = [["Jonah","87"],["Lucy","86"],["Kate","71"],["Jack","66"],["Lily","93"]];
I want to sort the results from the highest value to the lowest one like this:
Jack: 330
Lily: 266
Tom: 252
Emma: 249
Jonah: 241
Lucy: 232
Arnold: 159
Kate: 124
Marshall: 82
Ted: 62
Upvotes: 0
Views: 46
Reputation: 5308
You can make use of reduce
to sum the values by merging all of the arrays in to one, then apply sort()
for sorting based on score
:
var array01 = [["Jack","92"],["Tom","74"],["Lily","100"],["Jonah","62"],["Lucy","83"]];
var array02 = [["Tom","94"],["Emma","70"],["Jack","100"],["Arnold","91"],["Kate","53"]];
var array03 = [["Jack","72"],["Tom","84"],["Emma","91"],["Jonah","92"],["Lucy","63"]];
var array04 = [["Emma","88"],["Marshall","82"],["Arnold","68"],["Ted","62"],["Lily","73"]];
var array05 = [["Jonah","87"],["Lucy","86"],["Kate","71"],["Jack","66"],["Lily","93"]];
var all=[...array01,...array02,...array03,...array04,...array05];
var result = Object.values(all.reduce((acc, [key, val])=>{
acc[key] = acc[key] || {[key]:0};
acc[key][key]+=+val;
return acc;
},{})).sort((a,b)=>Object.values(b)[0]-Object.values(a)[0]);
console.log(result);
Upvotes: 2