JavaScript: Getting Unexpected Results When Filtering and Flattening Nested Arrays
I'm having a hard time understanding Quick question that's been bugging me - I'm currently working on a project where I need to filter out specific elements from a nested array and then flatten the result... However, I am running into an scenario where my output doesn't match my expectations. I am using JavaScript ES6 features, and here's the code I have so far: ```javascript const nestedArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; const filteredFlattenedArray = nestedArray .filter(subArray => subArray.some(num => num > 5)) .flat(); console.log(filteredFlattenedArray); ``` I expected `filteredFlattenedArray` to return `[6, 7, 8, 9]`, but instead, I get `[4, 5, 6, 7, 8, 9]`. It seems that the filter is not working as intended. After reviewing my logic, I realized that `filter` is returning any sub-array that contains at least one element greater than 5, which leads to including the entire sub-array in the result. To address this, I attempted using `reduce` to achieve what I needed: ```javascript const filteredArray = nestedArray.reduce((acc, subArray) => { const filteredSubArray = subArray.filter(num => num > 5); return [...acc, ...filteredSubArray]; }, []); console.log(filteredArray); ``` However, this also feels a bit inefficient because I'm creating a new array with spread syntax each time. Is there a more optimal way to both filter and flatten this nested array? Would using a single `flatMap` be suitable here, or would it lead to similar issues? Any pointers on best practices in this scenario would be greatly appreciated. This is part of a larger API I'm building. What am I doing wrong?