Front end interview questions - Summary of array flattening method

2021-08-26 17:40:00 stan

Flattening arrays

2. Convert to string

2.1 `toString` + `map` + `parseInt`

``````var arr = [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, [12, 13, [14, 15, 16]]], 17],
str = arr.toString(), // '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17'
strArr = str.split(','), // ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17']
res = strArr.map(item => parseInt(item)) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]``````

2.2 `toString` + `JSON.parse`

``````var arr = [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, [12, 13, [14, 15, 16]]], 17],
str = arr.toString(), // '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17'
jsonStr = '[' + str + ']', // '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]'
res = JSON.parse(jsonStr) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]``````

3. recursive

``````function flat(array) {
/*  recursive  */
var _res = [],
dfs = function (arr) {
for (let i = 0; i < arr.length; i++) {
Object.prototype.toString.call(arr[i]) === '[object Array]'
? dfs(arr[i])
: _res.push(arr[i])
}
}

dfs(array)

return _res
}``````

4. iteration

``````function flat(array) {
/*  iteration  */
var queue = [array],
res = [],
next

while (queue.length) {
next = queue.shift()

Object.prototype.toString.call(next) === '[object Array]'
? Array.prototype.push.apply(queue, next)
: res.push(next)
}

return res
}``````