// EXAMPLE input converted to a multiline stringconstinput=`1000
2000
3000
4000
5000
6000
7000
8000
9000
10000`// use my work from Part 1 to get the array of sums// make an array of sub-arrays where each sub-array is one elf's calories, i.e., one grouping of numsconstgroupedByElf=input// `1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000`.split('\n\n')// ['1000\n2000\n3000', '4000', '5000\n6000', '7000\n8000\n9000', '10000'].map(str=>str.split('\n').map(str=>+str))// [ [1000, 2000, 3000], [4000], [5000, 6000], [7000, 8000, 9000], [10000] ]// find the total for each grouping and put these totals in one arrayconsteachGroupSum=groupedByElf.map(subArr=>subArr.reduce((acc,curVal)=>acc+curVal))// [6000, 4000, 11000, 24000, 10000]// sort array from smallest to largestconsteachGroupSumSorted=eachGroupSum.sort((a,b)=>a-b)// [4000, 6000, 10000, 11000, 24000]// push and pop, push and pop, push and pop (3 times)letthreeHighest=[]threeHighest.push(eachGroupSumSorted.pop())threeHighest.push(eachGroupSumSorted.pop())threeHighest.push(eachGroupSumSorted.pop())// console.log(threeHighest) // [24000, 11000, 10000]// sum those three valuesconstsumOfThreeHighest=threeHighest.reduce((acc,curVal)=>acc+curVal)// log itconsole.log(sumOfThreeHighest)// 45000
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)