【问题标题】:Output object with same value at same position在相同位置输出具有相同值的对象
【发布时间】:2019-03-20 15:07:20
【问题描述】:

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

问题:如果同一个key的两个值相同,那么两个对象应该放在同一个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循环中的点键 喜欢

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

【问题讨论】:

  • 如果输入是 Bob,为什么 Mary 和 Kate 会被返回
  • 请看看我对另一个关于排序的问题的回答:stackoverflow.com/questions/5467129/…我相信这会对你有所帮助。
  • 扭转你的逻辑。如果 people[i-1] 不存在,则为第一等级。如果前人存在且分数相同,则排名与前人相同。否则它的previous.points + 1。

标签: javascript arrays object iteration comparison


【解决方案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);
});

【讨论】:

  • 嗨,克雷格·韦恩,谢谢。但是“John”在位置 4。他应该在 3。运行函数之后。我会在我的问题中澄清这一点。
  • @S.H.稍微调整了一下逻辑,现在可以了,来回抱歉
  • 非常感谢。现在我明白了……
【解决方案2】:

迭代时保留两个索引:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多