Find a function ranking(people)
which took an array of objects as input. Keys
are: Name
and Points
.
It should return a sorted array with the highest points on first position, the 2nd highest on second…
It should ad a third
key: Position
.
So far so good.
Problem: If two values of the same key are the same, then both objects should be placed on the same position.
Example:
ranking([{name: "John",points: 100},{ name: "Bob",points: 130},{name: "Mary", points: 120},{name: "Kate",points: 120}]);
Because Bob ranks highest, this objects should be returned at first. Mary and Kate are ranking at second. So both should be positioned at position: 2.
This is the part I am struggling with. My code so far (except the troubling part, which I put separated below)
function ranking(people) {
people.sort((a, b) => (a.points > b.points ? -1 : 1));
for (var i = 0; i < people.length; i++) {
Object.assign(people[i], { position: i + 1 });
}
console.log(people);
}
I tried to compare the points keys in the for-Loop like
if(people[i].points === people[i+1].points) {
people[i+1].position === i;
}
which does not work. I think I need to use map
or for…in
, but I don't know how…
EDIT:
The output should be:
name: "Bob", points: 130, position: 1
name: "Kate", points: 120, position: 2
name: "Mary", points: 120, position: 2
name: "John", points: 100, position: 3 **NOT 4**
After reading some of the hints I came up with:
for (var j = 1; j < people.length; j++) {
if (people[j - 1].points === people[j].points) {
people[j].position = j;
}
}
But than is the problem, that there is no position 3 – just a position: 4