-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_nestedArray.js
More file actions
34 lines (27 loc) · 878 Bytes
/
2_nestedArray.js
File metadata and controls
34 lines (27 loc) · 878 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
///// NESTED ARRAY ///////
const nestedArray = [[2,3],[2,6,7,9],87,12,[23,[56,22,[45,66,78]]]];
//Method1
var result = nestedArray.flat(Infinity);
console.log("Using Array.flat() : ", result);
//Method2
result = flattenTheArray(nestedArray);
console.log("Using for loop: ", result);
function flattenTheArray(arr){
let flatArray = [];
for(let i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
flatArray = flatArray.concat(flattenTheArray(arr[i]))
}else{
flatArray.push(arr[i]);
}
}
return flatArray;
}
//Method 3 Reduce method
result = flattenTheArrayUsingReduce(nestedArray);
console.log("Using reduce method: ", result);
function flattenTheArrayUsingReduce(arr){
return arr.reduce((acc, item)=>{
return acc.concat(Array.isArray(item)? flattenTheArrayUsingReduce(item):item)
}, []);
}