I have the below function, but it is not returning the desired result. How can I change this so it returns the desired output?
function convertArr () {
const separateNestedArrays = function (arr) {
return arr.flatMap((element) => {
if (Array.isArray(element)) {
return element;
} else {
return [element];
}
});
};
const twoDimensionalArray = [
[1, 2, 3, 4],
[[5, 6], [9, 10]],
[5, 6, 7]
];
const modifiedArray = separateNestedArrays(twoDimensionalArray);
console.log(modifiedArray);
// Desired Output: [[1, 2, 3, 4], [5, 6], [9, 10], [5, 6, 7]]
// Current Output: [ 1, 2, 3, 4, [ 5, 6 ], [ 9, 10 ], 5, 6, 7 ]
};
4
Answers
You could work with recursive functions but in your case if twoDimensionalArray is not going to be more than 2 dimensions this code could work :
That one is tricky. Flatmap doesn’t apply it’s flattening until the return, so you can’t work directly with it inside the handler. I think it’s a good opportunity for using Array.reduce
The function you want should flatten a single level if the array items also contains another array?
I’d write this using
reduce
, where youpush
your items into your accumulator (a new array).If the item contains another array, then push the items’ subitems, otherwise push the item itself.
That is confusing to type out, seeing some code might be easier.
Every time you encounter an array, create a new array in the accumulator (
a
). Then recursively push further items into the most recent array in the accumulator.Finally, discard any empty arrays in the result.