Input:
[1,2,[3,4,[5,6]]]
Output:
[[1,2],[3,4],[5,6]]
Provided below is a solution to the given problem:
function convert(a,res=[]) {
const group = (arr) => {
res.push(arr.slice(0,2));
arr.map((v) => Array.isArray(v) && group(v));
}
group(a);
return res;
}
console.log(convert([1,2,[3,4]])); // [[1,2],[3,4]]
console.log(convert([1,2,[3,4,[5,6]]])); // [[1,2],[3,4],[5,6]]
console.log(convert([1,2,[3,4,[5,6,[7,8]]]])); // [[1,2],[3,4],[5,6],[7,8]];
Although the initial problem is solved using a nested function approach, there's an attempt to refactor the code without it as shown below:
function convert(a,i=0,res=[]) {
return i >= a.length
? res
: convert(
a,
i+1,
Array.isArray(a[i]) ? [...res,a.slice(0,2)] : res
)
}
console.log(convert([1,2,[3,4]])); // [[1,2]]
console.log(convert([1,2,[3,4,[5,6]]])); // [[1,2]]
console.log(convert([1,2,[3,4,[5,6,[7,8]]]])); // [[1,2]]
However, the result is not as expected. Seeking feedback and pointers for improvement:
UPDATE:
Here is an updated solution that covers more test cases:
function convert(a,res=[]) {
return !a.length
? res
: convert(
a.filter(Array.isArray).flat(),
[...res,a.filter((v) => !Array.isArray(v))]
);
}
console.log(convert([1,2,[3,4]])); // [[1,2],[3,4]]
console.log(convert([1,2,[3,4,[5,6]]])); // [[1,2],[3,4],[5,6]]
console.log(convert([1,2,[3,4,[5,6,[7,8]]]])); // [[1,2],[3,4],[5,6],[7,8]];
console.log(convert([1,2,[5,6,[9,10],7,8],3,4])); // [[1,2,3,4],[5,6,7,8],[9,10]]
console.log(convert([1,5,5,[5,[1,2,1,1],5,5],5,[5]])); // [[1,5,5,5],[5,5,5,5],[1,2,1,1]]
console.log(convert([1,[2],1,[[2]],1,[[[2]]],1,[[[[2]]]]])); // [[1,1,1,1],[2],[2],[2],[2]]