如何根据数组中的上一个元素过滤元素

时间:2020-04-03 00:26:22

标签: javascript arrays algorithm data-structures ecmascript-6

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

    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" },
    ]
]

关于如何实现这一目标的任何建议?

1 个答案:

答案 0 :(得分:3)

只需将filter包围在.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);

相关问题