I recently went through some of the JS interviews where I was asked to implement a couple of custom implementations of well used JS functions. We use them on our day to day JS tasks. So I thought of sharing these with you all.

Although you might not ever need to come up with your own stuff but it’s good to understand and think of them natively.

If you’re not preparing for an interview and just want to learn about JavaScript in general, I invite you to come along and read through as you may gain something from this piece.


flat

flat flattens nested array to the desired level.

E.g.

const arr = [[1,2,3], 2,5,4,56, [4,5,[45,6,7]]];
const flatArr = arr.flat(1);
flatArr; // [1,2,3,2,5,4,56,4,5,[45,6,7]]

Here’s the custom implementation:

function customFlat(arr, level, resArr=[]){
 if(level === 0 )  return arr;
 
 for(let item of arr){
   if(Array.isArray(item)){
     resArr.push(...item);
   }else{
     resArr.push(item);
   }
 }
 resArr = customFlat(resArr, --level);
 
 return resArr;
}

customFlat takes in three arguments: arraylevelresult array(optional).

We simply loop through the array and check to see if the current item is an array; if it is we spread it in the resulting array otherwise we push the item directly. Thereafter we recursively call the flat function until the level is 0. We return our resulting array in the end.

Below is the usage:

const arr = [[1,2,3], 2,5,4,56, [4,5,[45,6,7]]];
const flatArr = customFlat(arr, 2);
flatArr; // [1,2,3,2,5,4,56,4,5,[45,6,7]]

#front-end-development #interview #software-development #javascript #web-development

Some of the JavaScript Interview Questions I have experienced
1.45 GEEK