gpt4 book ai didi

javascript - 根据对象的不同值过滤数组

转载 作者:行者123 更新时间:2023-12-03 07:16:57 24 4
gpt4 key购买 nike

我想简化对象数组的过滤。假设我有以下数组,

const users = [{
name: "user1",
gender: "m"
}, {
name: "user2",
gender: "f"
}, {
name: "user3",
gender: "f"
}, {
name: "user4",
gender: "m"
}, {
name: "user5",
gender: "m"
}];

例如我需要按男性或女性过滤所有用户,所以我循环过滤对象属性:

const fUsers = users.filter(user => user.gender === "f");
const mUsers = users.filter(user => user.gender === "m");

const results = [fUsers, mUsers];
console.log(results);

是否有更好的过滤方式来一次性完成,这样我就可以在多个数组中获得结果。

最佳答案

您可以使用 reduce 函数并在累加器中传递一个嵌套数组。在回调中检查性别,您可以使用 acc[0] 在累加器或 acc[1]

的第一个嵌套数组中添加元素

const users = [{
name: "user1",
gender: "m"
}, {
name: "user2",
gender: "f"
}, {
name: "user3",
gender: "f"
}, {
name: "user4",
gender: "m"
}, {
name: "user5",
gender: "m"
}];

const newArr = users.reduce((acc, curr) => {
if (curr.gender === 'f') {
acc[0].push(curr)
} else {
acc[1].push(curr)
}
return acc;
}, [
[],
[]
]);

console.log(newArr)

或者你也可以使用普通的for循环

const users = [{
name: "user1",
gender: "m"
}, {
name: "user2",
gender: "f"
}, {
name: "user3",
gender: "f"
}, {
name: "user4",
gender: "m"
}, {
name: "user5",
gender: "m"
}];

let arr = [
[],
[]
];
for (let i = 0; i < users.length; i++) {
users[i].gender === 'f' ? arr[0].push(users[i]) : arr[1].push(users[i])
};

console.log(arr)

关于javascript - 根据对象的不同值过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64467297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com