5 Ways to Flatten Arrays in JS

1. The idea of ​​ordinary recursion is easy to understand. It is forto flatten layer by layer and element by element by means of loops. If the current element is an array, then recursively process it, and then stitch the result of the recursive processing to the result array.

let arr = [1, [2, [3, 4, 5]]];
function flatten(arr) {
  let result = [];
  for(let i = 0; i < arr.length; i++) {
    // 当前元素是一个数组,对其进行递归展平
    if(Array.isArray(arr[i])) {
      // 递归展平结果拼接到结果数组
      result = result.concat(flatten(arr[i]));
    } 
    // 否则直接加入结果数组
    else {
      result.push(arr[i]);
    }
  }
  return result;
}
console.log(flatten(a));  //  [1, 2, 3, 4,5]

Two .    reduceIt is JSa very powerful method in the array, and it is also JSa functional programming in the array API.

The key to the above recursive implementation is to process each item of the array, and recursively process it when encountering an array. Since loops and result arrays are needed, we can simplify reduceour code by using:

let arr = [1, [2, [3, 4]]];
function flatten(arr) {
    return arr.reduce(function(pre, cur){
        return pre.concat(Array.isArray(cur) ? flatten(cur) : cur)
    }, [])
}
console.log(flatten(arr));//  [1, 2, 3, 4,5]

3. The spread operator is ES6one of the new features of the array. Using it to operate the array can directly expand the first layer of the array. With this feature, we can achieve the flattening of the array without using recursion.

let arr = [1, [2, [3, 4]]];
function flatten(arr) {
    while (arr.some(i => Array.isArray(i))) {
        arr = [].concat(...arr);
    }
    return arr;
}
console.log(flatten(arr)); //  [1, 2, 3, 4,5]

4. The implementation of regularization is also to convert the array into a string expression first. Here we use the JSON.stringify method to convert the array into a string wrapped in parentheses and separated by commas. The se method is parsed into an array object "[1, [2, [3, [4, 5]]], 6]".

let arr = [1, [2, [3, [4, 5]]], 6];
function flatten(arr) {
  let str = JSON.stringify(arr);
  str = str.replace(/(\[|\])/g, '');
  // 拼接最外层,变成JSON能解析的格式
  str = '[' + str + ']';
  return JSON.parse(str); 
}
console.log(flatten(arr)); //  [1, 2, 3, 4,5]

5.Array.prototype.flat It is ES6a newly added array method. Its function is to flatten the array and determine the level of expansion according to the parameters passed in. It is the ultimate solution to flatten the array

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

The above method can also flatten any type of array. I have tried it and can use it directly

Guess you like

Origin blog.csdn.net/weixin_48309048/article/details/128244666