前言
現(xiàn)在的前端面試手撕題是一個必要環(huán)節(jié),有點時候八股回答的不錯但是手撕題沒寫出來就會讓面試官印象分大減,很可能就掛了…
概念
數(shù)組的扁平化其實就是將一個多層嵌套的數(shù)組轉(zhuǎn)換為只有一層的數(shù)組
比如: [1, [2, [3, [4, 5]]]] => [1,2,3,4,5,6]
題目
一、實現(xiàn)一個 flat() easy 難度
function myFlat(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(myFlat(arr[i]));
// res = [...res, ...myFlat(arr[i])] 這樣寫也可以
} else {
result.push(arr[i])
}
}
return result
}
二、用遞歸實現(xiàn) medium 難度
const flat = arr => {
let res = []
let rStack = [...arr]
while (rStack.length) {
let top = rStack.shift()
if (Array.isArray(top)) {
rStack.unshift(...top)
} else {
res.push(top)
}
}
return res
}
三、控制扁平化的深度 medium 難度
depth 為展平的深度 比如 1 就是將整體深度減一
const myFlat = (arr, depth) => {
let result = []
for (const element of arr) {
if (Array.isArray(element) && depth > 0) {
result = [...result, ...myFlat(element, depth - 1)]
} else {
result.push(element)
}
}
return result
}
四、計算嵌套數(shù)組的深度 medium 難度
類似層序遍歷!文章來源:http://www.zghlxwxcb.cn/news/detail-623389.html
const getDepth = arr => {
const queue = [...arr]
let depth = 1
while (queue.length > 0) {
const curLen = queue.length
for (let i = 0; i < curLen; i++) {
const cur = queue.shift()
if (Array.isArray(cur)) {
queue.push(...cur)
}
}
depth++
}
return depth - 1
}
五、遞歸控制扁平化的深度 hard 難度文章來源地址http://www.zghlxwxcb.cn/news/detail-623389.html
function flattenArrayWithDepth(arr, depth) {
const flattenedArray = [];
const queue = [{ array: arr, remainingDepth: depth }];
while (queue.length > 0) {
const { array, remainingDepth } = queue.shift();
for (const item of array) {
if (Array.isArray(item) && remainingDepth > 0) {
queue.push({ array: item, remainingDepth: remainingDepth - 1 });
} else {
flattenedArray.push(item);
}
}
}
return flattenedArray;
}
到了這里,關(guān)于JavaScript 手撕大廠面試題數(shù)組扁平化以及增加版本 plus的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!