Write a flatten function in JavaScript that uses recursion to create an array containing all nested arrays in a single array. The function should pass the test:
it("longer list, no mutation, completely flat", function () { var data = [[[1],2,[3]],4,[5,6]]; var orig_data = data; expect(ms.flatten(data)).toEqual([1,2,3,4,5,6]); expect(data).toEqual(orig_data); });
function flatten(array){
let arr=[];
function helper(array){
for(let i = 0;i<array.length;i++){
let element=array[i];
if(Array.isArray(element)){
arr=arr.concat(flatten(element));
}
else{
arr.push(element);
}
}
}
helper(array);
return arr;
}
console.log(flatten([[[1],2,[3]],4,[5,6]]));
this the function of flatten you can use this function in your file
If you found this answer helpful please give a thumbs
Get Answers For Free
Most questions answered within 1 hours.