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

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

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

最佳答案

只需将您的过滤器放在.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/

相关文章:

algorithm - A* 寻路在迷宫中如何处理死胡同? (伪代码)

javascript - 在 jQuery Mobile 选择上调用刷新()时出错

javascript - Uncaught ReferenceError : refresh is not defined

javascript - AngularJS : assign asynchronous data to an array element in a for loop

objective-c - 嵌套的 NSUserDefaults 数组读/写

algorithm - 插入排序与冒泡排序算法

c - 如何将类图 AVL 树序列化到磁盘?

javascript - 将元素粘贴到滚动页面顶部然后将其移开?

c# - 使用 javascript 删除 webgrid 行?

c - 在除一个数字外没有重复的数组中找到重复的数字