What is flat() function in JavaScript ,how to implement it's polyfill.
Before starting to read this article, You must have good knowledge of 'this' keyword of JavaScript. If you want to learn about 'this' keyword ,Please Click here
The flat()
method creates a new array with all sub-array elements concatenated into it .
It does not alter this
(array on which flat is called) but instead returns a shallow copy that contains the same elements as the ones from the original array.
//Syntax
flat()
flat(depth=1)
depth
The depth specifies how deep a nested array should be flattened. Default value of depth is 1.
const arr=[1,2,3,[4,5,[6,7]],8,9];
//when we don't provide depth
console.log(arr.flat()) // [1,2,3,4,5,[6,7],8,9]
//in above case since depth was by default 1 ,so it is flattened at 1 level.
//now if we provide depth more than 1.
console.log(arr.flat(depth=2)) // [1,2,3,4,5,6,7,8,9]
// if we provide depth more than array's length it would not give you error , like in the above case if we give depth more than 2 answer would be same.
Its polyfill
const arr=[1,2,3,[4,5,[6,7]],8,9];
Array.prototype.myFlat= function(depth=1){
//here 'this' refers to the array on which myFlat() is applied
if(!Array.isArray(this)) throw new Error('must be applied on array');
let newArr=[];
this.forEach((item)=>{
if(Array.isArray(item)&&depth>0)
newArr.push(...item.myFlat(depth-1)); //if item is array again apply the same method
else
newArr.push(item);
});
return newArr;
}
console.log(arr.myFlat(2)); // [1,2,3,4,5,6,7,8,9]