Js Array Flattening Implementation Method Code Summary

  • 2021-09-20 19:07:41
  • OfStack

Title:

Please write an array flatter function. The effect is as follows:

var arr=['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4];
flat(arr) //a,b,c,2,d,e,f,g,3,4

Method 1: Use toString method to convert arr to a string, then divide split into an array, and then convert the elements in the array to a number type


var arr =['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4];
function flat(arr) {
 return arr.toString().split(',').map(function(item){
    return Number(item)
 })
}
console.log(flat(arr))

Method 2: toString format conversion is similar to method 1, which is hermit type conversion


var arr = ['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4];
//  Method 2 : toString (Format Conversion) 
var flag = function(arr) {
	let toString = Array.prototype.toString;
	Array.prototype.toString = function() {
		return this.join(',');
	};
	let result = arr + '';
	Array.prototype.toString = toString;
	return result;
};

console.log(flag(arr));

Method 3: valueOf (Format Conversion) is similar to Method 1 2, which is the principle of hermit type conversion


//  Method 3 : valueOf( Format conversion )
Array.prototype.valueOf = function() {
	return this.join(',');
};

var flat = function(arr) {
	return arr + '';
};
console.log(flat(['a', ['b', 'c'], 2, ['d', 'e', 'f'], 'g', 3, 4]));

Method 4: Take advantage of reduce features


function flat(arr) {
	return newArr = arr.reduce((a, b) => {
		return a.concat(b)
	}, [])
}
var arr = ['a', ['b', 'c'], '2', ['d', 'e', 'f'], 'g', 3, 4];
console.log(flat(arr));

Method 5: Using recursion


function flat(array) {
	var result = [];
	var each = function(arr) {
		arr.forEach(item => {
			if (item instanceof Array) {
				each(item);
			} else {
				result.push(item);
			}
		});
	};
	each(array);
	return result.join(',');
}
var arr = ['a', ['b', 'c', [7, 8]], 2, ['d', 'e', 'f'], 'g', 3, 4];
console.log(flat(arr));

Method 6: Iterator of ES6 to add a traverser to the data structure, one next method must be added


// Iterator
Array.prototype[Symbol.iterator] = function() {
	let arr = [].concat(this);
	// arr=['a', ['b', 'c'], '2', ['d', 'e', 'f'], 'g', 3, 4]
	let getFirst = function(array) {
		let first = array.shift();
		if (first instanceof Array) {
			if (first.length > 1) {
				arr = first.slice(1).concat(array);
			}
			first = first[0];
		}
		return first;
	};
	return {
		next: function() { // Similarity and traversal 
			let item = getFirst(arr);
			if (item) {
				return {
					value: item,
					done: false,
				};
			} else {
				return {
					done: true,
				};
			}
		},
	};
};
var flat = function(arr) {
	let r = [];
	for (let i of arr) {
		r.push(i);
	} // i  Already a single element 
	return r.join(',');
};
var arr = ['a', ['b', 'c'], '2', ['d', 'e', 'f'], 'g', 3, 4];
console.log(flat(arr));

Related articles: