-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflattenArray.js
More file actions
34 lines (29 loc) · 894 Bytes
/
flattenArray.js
File metadata and controls
34 lines (29 loc) · 894 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
// Withour using .flat(), create a function to flatten an array
// const exampleArray = [1, 2, [3, 4, [5, 6, 7], 8], 9, 10]
// flatten(exampleArray); // [1, 2, 3, 4, 5, 6, 7, 8, 8, 10];
function flatten(array) {
let newArray = [];
for(let i = 0; i < array.length; i++) {
if(Array.isArray(array[i])) {
newArray = newArray.concat(flatten(array[i]));
} else {
newArray.push(array[i]);
}
}
return newArray;
}
var exampleArray = [1, 2, [3, 4, [5, 6, 7], 8], 9, 10];
// console.log(flatten(exampleArray));
function flatten2(array) {
let newArray = [];
newArray = array.reduce((acc, item) => {
if(Array.isArray(item)) {
acc = acc.concat(flatten2(item));
} else {
acc.push(item);
}
return acc;
}, []);
return newArray;
}
// console.log(flatten2(exampleArray));