在相同位置输出具有相同值的对象

时间:2019-03-20 15:07:20

标签: javascript arrays object iteration comparison

找到一个function ranking(people),该对象将一组对象作为输入。 Keys是:NamePoints。 它应该返回一个排序的数组,该数组的最高点在第一位,第二高在第二位…… 它应带有third键:Position。 到目前为止一切顺利。

问题:如果同一个键的两个值相同,则两个对象都应放在相同的position.

示例:

ranking([{name: "John",points: 100},{ name: "Bob",points: 130},{name: "Mary", points: 120},{name: "Kate",points: 120}]);

由于Bob排名最高,因此应首先返回此对象。玛丽和凯特排名第二。因此,两者都应位于以下位置:2.

这是我正在努力的部分。到目前为止,我的代码(麻烦的部分除外,我在下面将其分开放置)

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);
}

我试图比较for-loop中的点键 喜欢

if(people[i].points === people[i+1].points) {
people[i+1].position === i;
}

这不起作用。我认为我需要使用mapfor…in,但是我不知道如何……

编辑:

输出应为:

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** 

在阅读了一些提示后,我想到了:

   for (var j = 1; j < people.length; j++) {
     if (people[j - 1].points === people[j].points) {
       people[j].position = j;
     }
   }

但问题不在于,这里没有职位3 –只有position: 4

2 个答案:

答案 0 :(得分:1)

var data = [{name: "John",points: 100},{ name: "Bob",points: 130},{name: "Mary", points: 120},{name: "Kate",points: 120}];

//Sorts the object array by the points key
data.sort( (currentItem, nextItem) => {
    return currentItem.points > nextItem.points ? -1 : 1;
});

//add in those positions by comparing each item to the one before
data.forEach( (item, index) => {

    item.position = index+1;
    if( 0 === index ){
        return;
    }
    
    let previousItem = data[index-1];
    item.position = previousItem.points === item.points ? previousItem.position : previousItem.position+1;
});


data.forEach( i => {
 console.log(i);
});

答案 1 :(得分:0)

迭代时保留两个索引:

people.sort((a, b) => (a.points > b.points ? -1 : 1));

let position = 1;
for (var i = 0; i < people.length; i++) {
  Object.assign(people[i], { position });
  if(!i || people[i - 1].points > people[i].points) 
    position += 1;
}

return people;

或者如果您想要一个单线纸:

people
  .sort((a, b) => a.points - b.points)
  .reduce((prev, curr) => (curr.position = prev.position + (curr.points < prev.points), curr), { position: 0, points: -Infinity });

return people;