简体   繁体   English

如何在不更改原始数组的情况下过滤嵌套数组?

[英]How can I filter a nested array without mutating the original array?

I would like to return both the inner and outer array such as the following: [[3],[4],[5]]; 我想同时返回内部数组和外部数组,例如: [[3],[4],[5]];

This does not work: 这不起作用:

var arr = [[1],[2],[3],[4],[5]];

arr.filter(function(el){
    return el.filter(function(inner){
        return inner >= 3;
    });
});

This does not work either: 这也不起作用:

var arr = [[1],[2],[3],[4],[5]];

arr.map(function(el){
    return el.filter(function(inner){
        return inner >= 3;
    });
});

You can use array destructuring to get easy access to the inner array elements in the callback function: 您可以使用数组解构来轻松访问回调函数中的内部数组元素:

 const array = [[1],[2],[3],[4],[5]]; const filtered = array.filter(([inner]) => inner >= 3); console.log(array); // original console.log(filtered); // filtered 

map() and filter() functions don't mutate the array, they return a new array with the resulting items. map()和filter()函数不会改变数组,它们会返回一个包含结果项的新数组。

In the code you show us you're not assigning the result anywhere, also, you're trying to compare an array with a number: 在显示给我们的代码中,您没有将结果分配到任何地方,而且,您正在尝试将数组与数字进行比较:

If you wanted to return the values inside of their wrapping arrays, you would do it like this: 如果要返回其包装数组内部的值,则可以这样操作:

var arr = [[1],[2],[3],[4],[5]];

var newArr = arr.filter(function(inner){
    return inner[0] >= 3;
});

// newArr = [[3], [4], [5]]

you don't need the map function if you're only filtering. 如果只进行过滤,则不需要map函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM