【发布时间】:2020-07-15 02:49:30
【问题描述】:
假设您有以下代码来过滤动物,以便仅保存比数组中前一个动物更重的那些(第一个对象将永远不会被保存,因为没有前一个动物):
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" },
]
]
关于如何实现这一点的任何建议?
【问题讨论】:
标签: javascript arrays algorithm data-structures ecmascript-6