Several ways to achieve array flattening in js

Array flattening

The flattening of an array is to convert a nested multi-level array into an array with only one level. Flattening is also a common test question in interviews. As a simple example, suppose there is a function named flatDeep that can achieve the flattening effect of an array. The code running effect is as follows:

var array = [1, [2, [3, [4, 5]]]];
console.log(flatDeep(array)); // [1, 2, 3, 4,5]

There are several ways to implement the flatDeep function that can achieve flattening as mentioned above. Let's try these ways to implement a flatDeep function.

Method 1: Recursion

Through loop recursion, the array is traversed one by one. If each item is still an array, then continue to traverse down. The implementation is as follows:

var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr){
	let result = [];
	for(let i = 0; i < arr.length; i++) {
		if(Array.isArray(arr[i])){
			result = result.concat(flatDeep(arr[i]))
		} else {
			result.push(arr[i])
		}
	}
	return result;
}
console.log(flatDeep(array));
Method 2: Combining toString and split

First convert the array into a String object through toString(), then use the split() method to split the String object into a string array using comma delimiters, and then use the map function to convert the strings in the array into numbers.

var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr){
	let result = [];
	return result = arr.toString().split(',').map(Number)
}
console.log(flatDeep(array));
Method 3: Use the reduce function

Using the reduce method to accumulate effects, the implementation idea is somewhat similar to the conventional recursive method. The code is as follows:

var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr){
	return arr.reduce(function(pre,next){
		if(Array.isArray(next)){
			return pre.concat(flatDeep(next))
		} else {
			return pre.concat(next)
		}
	}, [])
}
// 以上代码还可用三目运算符做如下简化
function flatDeep(arr) {
	return arr.reduce((pre, next) => {
		return pre.concat(Array.isArray(next) ?  flatDeep(next) : next)
	},[])
}
console.log(flatDeep(array));
Method 4: Combine spread operator with some function

First use the some method of the array to filter out the items in the array that are still group numbers, then perform the concat operation, use the ES6 spread operator to splice them into the original array, and finally return the original array. code show as below:

var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr) {
	while(arr.some(item => Array.isArray(item))){
		arr = [].concat(...arr)
	}
	return arr;
}
console.log(flatDeep(array)); // [ 1, 2, 3, 4, 5 ]
Method 5: ES6 flat method

The flat() method will recursively traverse the array according to a specifiable depth, and merge all elements with the elements in the traversed sub-array into a new array and return it. The syntax is:

var newArray = arr.flat([depth])

The parameter depth specifies the depth of the structure to be extracted from the nested array, and the default value is 1. The parameter depth can also be passed into Infinity, which means that no matter how many layers there are, they must be expanded. The flat code effect achieved using the flat method is as follows:

var array = [1, [2, [3, [4, 5]]]];
function flatDeep(arr) {
	return arr.flat(Infinity)
}
console.log(flatDeep(array)); // [ 1, 2, 3, 4, 5 ]

Guess you like

Origin blog.csdn.net/2301_77456141/article/details/134186898