有条件地操作数组中元素的属性

2024-01-26

我是 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}
];

该数组列出了每个人的id, value,以及他们是谁friends和。例如,人物 1 是人物 3 的朋友,人物 3 是人物 5 的朋友,依此类推。

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

IF人的价值在于lowest or the 第二低数组中的值,THEN添加此人的 idhighest数组中的值给他们的朋友。

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

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

您可以传递源数组一次来计算出最高、最低和第二低的值(以及相应的值)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%;}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有条件地操作数组中元素的属性 的相关文章

随机推荐