gpt4 book ai didi

javascript - 如何根据数组数组中的前一个元素过滤元素

转载 作者:行者123 更新时间:2023-11-28 16:42:13 25 4
gpt4 key购买 nike

假设您有以下代码来过滤动物,以便仅保存那些比数组中前一个动物更重的动物(第一个对象永远不会被保存,因为没有前一个动物):

    const animals = [
{ id: 3, weight: 300, type: 'pig' },
{ id: 1, weight: 200, type: "cow" },
{ id: 7, weight: 400, type: "horse" },
{ id: 6, weight: 100, type: "pig" },
];


const filteredAnimals = animals.filter((animal, index) =>
animals[index - 1] && animal.weight > animals[index - 1].weight);

console.log('filtered animals: ', filteredAnimals);

这按预期工作,但我无法弄清楚如何应用具有数组数组的相同过滤器:

const animals = [
[
{ id: 5, weight: 300, type: 'pig' },
{ id: 1, weight: 200, type: "cow" },
{ id: 3, weight: 400, type: "horse" },
{ id: 4, weight: 350, type: "pig" },
],
[
{ id: 2, weight: 250, type: "horse" },
{ id: 6, weight: 350, type: 'pig' },
{ id: 8, weight: 250, type: "cow" },
{ id: 7, weight: 400, type: "pig" },
]
]

在这种情况下,预期结果应该是:

const filteredAnimals = [
[
{ id: 3, weight: 400, type: "horse" },
],
[
{ id: 6, weight: 350, type: "pig" },
{ id: 7, weight: 400, type: "pig" },
]
]

关于如何实现这一目标有什么建议吗?

最佳答案

只需将您的过滤器放在.map中,即可迭代所有子数组:

const animals = [
[
{ id: 5, weight: 300, type: 'pig' },
{ id: 1, weight: 200, type: "cow" },
{ id: 3, weight: 400, type: "horse" },
{ id: 4, weight: 350, type: "pig" },
],
[
{ id: 2, weight: 250, type: "horse" },
{ id: 6, weight: 350, type: 'pig' },
{ id: 8, weight: 250, type: "cow" },
{ id: 7, weight: 400, type: "pig" },
]
]


const filteredAnimals = animals.map(
subarr => subarr.filter((animal, index) =>
subarr[index - 1] && animal.weight > subarr[index - 1].weight
)
);
console.log(filteredAnimals);

关于javascript - 如何根据数组数组中的前一个元素过滤元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003326/

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