-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFlattenArray.js
More file actions
42 lines (34 loc) · 902 Bytes
/
FlattenArray.js
File metadata and controls
42 lines (34 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
let arr = [1,2,3,[4], [5,[6,7]], [8,[9,[10,11,12],13]],14,[15]];
/**
* @returns an array after flattening
* based on the parameters
*/
function funFlat(){
let result = [];
flatten(this);
function flatten(arr){
for(let i=0; i<arr.length; i++){
/**
* Check if the item is array
* If yes, then recursively call the function
* otherwise push that element to the result
*/
const currentElement = arr[i];
if(Array.isArray(currentElement)){
flatten(currentElement);
}
else{
result.push(currentElement);
}
}
}
return result;
}
Array.prototype.funFlat = funFlat;
let res = arr.funFlat();
console.log(res);
/**
* Follow-up Tasks-
* 1. Add Depth Parameter
* 2. Return the same array instead of a new one
*/