-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrayFlatten.js
76 lines (67 loc) · 1.96 KB
/
arrayFlatten.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Approach 1: Flatten by spread operator
function flattenArray1 (array = []) {
const flatArray = []
array.forEach(value => {
if (Array.isArray(value)) {
flatArray.push(...flattenArray1(value))
} else {
flatArray.push(value)
}
})
return flatArray
}
// Approach 2: Flatten by apply method
function flattenArray2 (array = []) {
const flatArray = []
array.forEach(value => {
if (Array.isArray(value)) {
[].push.apply(flatArray, flattenArray2(value))
} else {
flatArray.push(value)
}
})
return flatArray
}
// Approach 3: Let concat do magic flattening
function flattenArray3 (array = []) {
let flatArray = []
array.forEach(value => {
if (Array.isArray(value)) {
flatArray = flatArray.concat(flattenArray3(value))
} else {
flatArray = flatArray.concat(value)
}
})
return flatArray
}
// Approach 4: Reduce array to flat array
function flattenArray4 (array = []) {
return array.reduce((flatArray, value) => {
if (Array.isArray(value)) {
return flatArray.concat(flattenArray4(value))
} else {
return flatArray.concat(value)
}
}, [])
}
// Approach 5: Streamline it
function flattenArray5 (array = []) {
return array.reduce((flatArray, value) => {
return Array.isArray(value)
? flatArray.concat(flattenArray5(value))
: flatArray.concat(value)
}, [])
}
const shallowNestedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
const deepNestedArray = [1, [2, [3, [4, 5], [6], [7]]]]
console.log([].concat(...shallowNestedArray))
console.log([].concat(...deepNestedArray))
console.log([].concat.apply([], shallowNestedArray))
console.log([].concat.apply([], deepNestedArray))
// console.log(shallowNestedArray.flat(1))
// console.log(deepNestedArray.flat())
console.log(flattenArray1(deepNestedArray))
console.log(flattenArray2(deepNestedArray))
console.log(flattenArray3(deepNestedArray))
console.log(flattenArray4(deepNestedArray))
console.log(flattenArray5(deepNestedArray))