首页 > 解决方案 > 有条件地操作数组中元素的属性

问题描述

我是 javascript 新手,并试图通过玩具示例学习一些基础知识。

假设我有一个包含六个人数据的数组。

const myArray = [
    {"id": 1, "value": 75, "friends": 3},
    {"id": 2, "value": 40, "friends": 4},
    {"id": 3, "value": 60, "friends": 5},
    {"id": 4, "value": 62, "friends": 6},
    {"id": 5, "value": 55, "friends": 1},
    {"id": 6, "value": 33, "friends": 2}
];

该数组列出了每个人的idvalue和他们friends在一起的人。例如,第 1 个人是第 3 个人的朋友,第 3 个人是第 5 个人的朋友,以此类推。

现在我想根据每个人的价值来操纵谁和谁成为朋友。这是我想要实现的逻辑(可能在 for 循环中):

如果人的值是数组中的最低值或次低值,则将数组中 最高的 id 添加他们的朋友中。

所以在这种情况下我想要的输出是:

const myArray = [
    {"id": 1, "value": 75, "friends": 3},
    {"id": 2, "value": 40, "friends": [4, 1]},
    {"id": 3, "value": 60, "friends": 5},
    {"id": 4, "value": 62, "friends": 6},
    {"id": 5, "value": 55, "friends": 1},
    {"id": 6, "value": 33, "friends": [2, 1]}
];

我怎样才能做到这一点?


我已经对下面的数组进行了非常基本的操作,在这里我带走了数组中值最高的人的朋友。但是当我开始从事这项更复杂的任务时,我感到困惑。

const myArray = [
    {"id": 1, "value": 75, "friends": 3},
    {"id": 2, "value": 40, "friends": 4},
    {"id": 3, "value": 60, "friends": 5},
    {"id": 4, "value": 62, "friends": 6},
    {"id": 5, "value": 55, "friends": 1},
    {"id": 6, "value": 33, "friends": 2}
];

// Finds max and min values in array
var highest = Number.NEGATIVE_INFINITY;
var tmp;
for (var i=myArray.length-1; i>=0; i--) {
    tmp = myArray[i].value;
    if (tmp > highest) highest = tmp;
};

for(i = 0; i < myArray.length; i++){
    // If person has the highest value in the array
      if(myArray[i].value == highest){
        // Then take away their friend
        myArray[i].friends = NaN
      } else {
        myArray[i].friends = myArray[i].friends
      }
  };

  console.log(myArray);

标签: javascriptarrays

解决方案


您可以传递一次源数组以计算出最高、最低和次低的值(以及相应id的 's),然后在到达末尾时相应地修改您的源数组:

const src = [
    {"id": 1, "value": 75, "friends": 3},
    {"id": 2, "value": 40, "friends": 4},
    {"id": 3, "value": 60, "friends": 5},
    {"id": 4, "value": 62, "friends": 6},
    {"id": 5, "value": 55, "friends": 1},
    {"id": 6, "value": 33, "friends": 2}
],
    
    populateFriends = input => {
      let highest = {value: -Infinity},
          lowest = {value: Infinity},
          secondLowest = {}
      for({id, value} of input){
          if(value > highest.value){
            highest = {id, value}
          } else if(value < lowest.value){
            secondLowest = {...lowest}
            lowest = {id, value}
          }
      }
      return input.map(o => 
        (o.id == lowest.id || o.id == secondLowest.id) && 
        o.friends != highest.id ? 
        {...o, friends: [o.friends, highest.id]} :
        o)
    }
    
console.log(populateFriends(src))
.as-console-wrapper{min-height:100%;}


推荐阅读