javascript - 有条件地操作数组中元素的属性
问题描述
我是 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 循环中):
如果人的值是数组中的最低值或次低值,则将数组中 值最高的人的 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);
解决方案
您可以传递一次源数组以计算出最高、最低和次低的值(以及相应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%;}
推荐阅读
- reactjs - React 自定义钩子不会更新状态
- javascript - 将数组中的所有元素加入单个字符串后无法更新 React.useState("")
- html - 使用 jQuery 提取 XML 中的 CDATA 以用作 HTML
- nopcommerce - Nopcommerce 导出用户角色
- react-native - 如何使用 React Native 在应用程序图标上显示消息数量?(适用于安卓和IOS)
- latex - 我无法打开样式文件 IEEEbib.bst
- javascript - 如何使用reduce计算数组中的项目?
- python - SWIG 将 Python 列表转换为 char ** 示例失败
- email - 当我的网站出现错误时,我想发送一封电子邮件,但我有一些错误
- maven - 如何获取/获取 Jenkins 管道中设置的环境变量到我们的 maven pom.xml