3

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;
    });
});
1
  • The inner array always only has one element? Commented Jun 13, 2019 at 3:08

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. Thank you
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.