【问题标题】:How to filter element depending on the previous element in an array of arrays如何根据数组数组中的前一个元素过滤元素
【发布时间】: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


    【解决方案1】:

    只需将您的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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      相关资源
      最近更新 更多