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

Viewed 438

I would like to return both the inner and outer array such as the following: [[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;
    });
});
2 Answers

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.

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.

Related