You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this:
class Student {
constructor(name, fives, tens, twenties) {
this.name = name;
this.fives = fives;
this.tens = tens;
this.twenties = twenties;
}
}
As you can tell, each Student has some fives, tens, and twenties. Your job is to return the name of the student with the most money. If every student has the same amount, then return "all".
Notes:
Each student will have a unique name
There will always be a clear winner: either one person has the most, or everyone has the same amount
If there is only one student, then that student has the most money
I've tried this:
function mostMoney(students) {
//get array of totals
let array = [];
students.forEach((value, index) => {
let total = ((5 * value.fives) + (10 * value.tens) + (20 * value.twenties));
array.push([total, value.name]);
});
//sort array of totals
array = array.sort((a, b) => b[0] - a[0]);
console.log('array****', array);
//check if all totals are equal - if they are, return 'all'
if (array.every((el, i, array) => (el)[0]) === array[0][0]) {
return 'all';
}
else {
return array[0][1];
}
}
What doesn't make sense to me is that when I console.log('array****', array);
in codewars it looks like:
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'David' ] ]
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'Cameron' ],
[ 30, 'Geoff' ],
[ 30, 'David' ] ]
array**** [ [ 40, 'Andy' ] ]
array**** [ [ 40, 'Stephen' ] ]
array**** [ [ 30, 'Cameron' ], [ 30, 'Geoff' ] ]
Why does it look like that? I would think that after sorting, my console.log('array***', array)
should just look like:
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'Cameron' ],
[ 30, 'Geoff' ],
[ 30, 'David' ] ]
When I initially console.log(students)
, it looks like an array:
[ Student { name: 'Andy', fives: 0, tens: 0, twenties: 2 },
Student { name: 'Stephen', fives: 0, tens: 4, twenties: 0 },
Student { name: 'Eric', fives: 8, tens: 1, twenties: 0 },
Student { name: 'David', fives: 2, tens: 0, twenties: 1 },
Student { name: 'Phil', fives: 0, tens: 2, twenties: 1 } ]
So I'm trying to collect all of the totals in an array with my forEach
loop, and then sorting that array after looping - what's wrong with that logic?