An array-related question frequently asked in interviews.
Interviewer: I will give you a multi-level array
[1,[2,34,[12,4]],23]
. What are the methods to achieve the flattening of the array? You can talk about everything you can think of.
You: Doesn't ES6 provide a function,
flatten
, just use it for flattening
Interviewer: Well, is there any other way besides this? or make your own
You: No, I use it directly
Interviewer: Mental activity, do you think I don't know this function? Do I just want to ask you about this function? The days of basically the first interview question are dead.
In fact, the interviewer's purpose is not to make things difficult for you, but to examine your JavaScript foundation through such a JavaScript interview question. If you read this article, and clarify these 6 flattened functions, and explain the general idea Come out, I believe that the interviewer should be quite satisfied with the basics of JavaScript.
Let's start our study
Method 1: Use the most basic recursive traversal method
Use the basic traversal method, and then whether the traversed item item is an array, if it is an array, execute the flattening function recursively, and contact the result of the execution with the previous contact, if the item item is not an array, directly push the value to the initially defined array.
let array = [1,[2,34,[12,4]],23];
function flatten(array){
let result = []
for (const item of array) {
if(Array.isArray(item)){
result = result.concat(flatten(item))
}else{
result.push(item)
}
}
return result
}
console.log(flatten(array))
Method 2: Use reduce function for recursive operation
function flatten(array){
return array.reduce((pre,current,currentIndex,array)=>{
if(Array.isArray(current)){
return pre.concat(flatten(current))
}else{
return pre.concat(current)
}
},[])
}
Method 3: while loop combined with findIndex and spread operator
Implementation idea: use while
loop , loop to judge the condition, concat
whether the array type is included in the future array, if it is included, then use the ...
spread operator to expand and merge
let array = [1,[2,34,[12,4]],23]
function flatten(array){
while(array.findIndex((item)=>Array.isArray(item)>0)){
array = [].concat(...array)
}
return array
}
console.log(flatten(array))
Method 4: Array coercion type conversion
Implementation idea: cast the array to type, then use to split
separate it into an array, and finally be careful not to forget to convert to Number
type
function flatten(array){
return array.toString().split(',').map(item=>Number(item)) // 'array.toString() 转换后的结果 1,2,34,12,4,23'
}
console.log(flatten(array))
Approach 5: Using JSON's Functions and Regular Expressions
Implementation idea: first use JSON.stringify
to convert the array, then use regular matching to remove [ ]
, add in the outermost layer [ ]
, and finally use JSON.parse
Convert
let array = [1,[2,34,[12,4]],23];
function flatten(array){
let result = JSON.stringify(array); // JSON.stringify 转换后的结果 '[1,[2,34,[12,4]],23]'
result = result.replace(/(\[|\])/g,'');
result = '[' + result + ']';
return JSON.parse(result)
}
console.log(flatten(array));
Approach 6: Flattening using stack and spread operator
Implementation idea: create a 栈
structure, an empty array, and then traverse the stack structure, determine if it is an array, use the spread operator to expand and throw it into the stack again, if not, add it to the head of the newly created array
function flatten(arr) {
let res = [];
const stack = [].concat(arr);
console.log('哈哈哈',stack)
while (stack.length > 0) {
console.log(stack.length,stack)
const item = stack.pop();
if (Array.isArray(item)) {
// 用扩展运算符展开一层
stack.push(...item);
} else {
item !== undefined && res.unshift(item);
}
}
return res;
}
console.log(flatten(array))
Approach 7: Using the flatten function in ES6
Implementation idea: The syntax for flattening directly using the flatten function provided by ES6 is arr.flatten([depth]) depth can pass the expansion depth of the array, (the value is 1 when not filled by default), that is, expand a layer of array . Infinity
It means that no matter how many layers are expanded, other integers can also be set to expand a fixed number of layers
let array = [1,[2,34,[12,4]],23]
function flatten(array){
return array.flat(Infinity)
}
console.log(flatten(array))
After talking about this 6
method , you will find ES6
that the functions provided are elegant, and the parameters for the number of flattening layers are also provided, so that the number of flattening layers can be selectively flattened, so leave it as a homework, and modify the above functions to support layers Number flattening, ideas (flattened layer support is actually controlled by traversal/recursion)
Node 社群
我组建了一个氛围特别好的 Node.js 社群,里面有很多 Node.js小伙伴,如果你对Node.js学习感兴趣的话(后续有计划也可以),我们可以一起进行Node.js相关的交流、学习、共建。下方加 考拉 好友回复「Node」即可。
如果你觉得这篇内容对你有帮助,我想请你帮我2个小忙:
1. 点个「在看」,让更多人也能看到这篇文章2. 订阅官方博客 www.inode.club 让我们一起成长
点赞和在看就是最大的支持❤️