8 Ways to Flatten Arrays in JS

The usage scenarios and advantages and disadvantages of eight array flattening methods

The following are the usage scenarios and advantages and disadvantages of the eight array flattening methods:

1. Use recursion:

  • Usage scenario: When you need to flatten nested arrays of any level, recursion is a simple and general method.
  • Advantages: Simple and easy to understand, suitable for nested arrays of any level.
  • Disadvantages: There may be performance issues, and for very large arrays or multi-level nested arrays, recursion may cause stack overflow.

2. Use the reduce method:

  • Usage scenario: The reduce method is a common choice when you need to perform a series of operations on an array and accumulate the results into a new array.
  • Advantages: the code is concise, and the flattening logic can be directly processed in the reduce method.
  • Disadvantage: The reduce method can cause performance issues for very large arrays or multi-level nested arrays.

3. Use the spread operator:

  • Usage scenario: When it is necessary to quickly flatten a multi-level nested array into a one-dimensional array, the spread operator is a simple and intuitive method.
  • Advantages: The code is concise, easy to understand and use.
  • Disadvantage: The spread operator can cause performance problems for very large arrays or for arrays that are nested multiple levels.

4. Use the flat method (ES2019):

  • Usage scenario: In an environment that supports ES2019, the flat method can be used to flatten the array.
  • Advantages: the code is concise, the built-in method is used, and the performance is better.
  • Disadvantages: Not suitable for environments that do not support ES2019.

5. Use the toString and split methods:

  • Usage scenario: When you need to convert a multi-level nested array into a string and use the string method for processing, you can use the toString and split methods.
  • Advantages: Simple and easy to understand, suitable for simple flat requirements.
  • Disadvantages: For arrays containing object or string elements, unexpected results may occur.

6. Using regular expressions and JSON methods:

  • Usage scenario: This method can be used when an array needs to be converted into a string and then processed with regular expressions and JSON methods.
  • Advantages: Suitable for simple flat requirements.
  • Disadvantages: For arrays containing object or string elements, unexpected results may occur.

7. Use the stack:

  • Usage scenario: When you need to manually control the processing order of array elements, you can use the stack method.
  • Advantages: You can flexibly control the processing order, which is suitable for situations that require custom processing logic.
  • Cons: Relatively complex, requires manual handling of the stack and result array.

8. Using the spread operator and recursion:

  • Usage scenario: This method can be used when it is necessary to combine the spread operator and recursion to process multi-level nested arrays.
  • Advantages: The code is concise and combines the advantages of the spread operator and recursion.
  • Disadvantage: For very large arrays or arrays with multiple levels of nesting, recursion can lead to stack overflow.

According to the specific needs and code environment, choose the appropriate method to achieve array flattening. Consider factors such as performance, code complexity, and readability, and choose the most suitable method for implementation.

Implementation

Here are 8 ways to flatten your array:

1. Use recursion:

function flatten(arr) {
    
    
  let result = [];
  arr.forEach(item => {
    
    
    if (Array.isArray(item)) {
    
    
      result = result.concat(flatten(item));
    } else {
    
    
      result.push(item);
    }
  });
  return result;
}

2. Use the reduce method:

function flatten(arr) {
    
    
  return arr.reduce((result, item) => {
    
    
    if (Array.isArray(item)) {
    
    
      result = result.concat(flatten(item));
    } else {
    
    
      result.push(item);
    }
    return result;
  }, []);
}

3. Use the spread operator:

function flatten(arr) {
    
    
  while (arr.some(item => Array.isArray(item))) {
    
    
    arr = [].concat(...arr);
  }
  return arr;
}

4. Use the flat method (ES2019):

function flatten(arr) {
    
    
  return arr.flat(Infinity);
}

5. Use the toString and split methods:

function flatten(arr) {
    
    
  return arr.toString().split(',').map(item => +item);
}

6. Using regular expressions and JSON methods:

function flatten(arr) {
    
    
  return JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']');
}

7. Use the stack:

function flatten(arr) {
    
    
  const stack = [...arr];
  const result = [];
  while (stack.length) {
    
    
    const next = stack.pop();
    if (Array.isArray(next)) {
    
    
      stack.push(...next);
    } else {
    
    
      result.unshift(next);
    }
  }
  return result;
}

8. Using the spread operator and recursion:

function flatten(arr) {
    
    
  return [].concat(...arr.map(item => Array.isArray(item) ? flatten(item) : item));
}

These methods can flatten multi-level nested arrays into one-dimensional arrays. Which method to use depends on your needs and code environment.

encapsulation

The following is an example of encapsulating the eight methods into their own functions and calling them:

// 1. 使用递归
function flattenByRecursion(arr) {
    
    
  let result = [];
  
  function flattenHelper(arr) {
    
    
    for (let i = 0; i < arr.length; i++) {
    
    
      if (Array.isArray(arr[i])) {
    
    
        flattenHelper(arr[i]);
      } else {
    
    
        result.push(arr[i]);
      }
    }
  }
  
  flattenHelper(arr);
  return result;
}

// 2. 使用 reduce 方法
function flattenByReduce(arr) {
    
    
  return arr.reduce((acc, cur) => {
    
    
    return Array.isArray(cur) ? acc.concat(flattenByReduce(cur)) : acc.concat(cur);
  }, []);
}

// 3. 使用扩展运算符
function flattenBySpreadOperator(arr) {
    
    
  while (arr.some(item => Array.isArray(item))) {
    
    
    arr = [].concat(...arr);
  }
  return arr;
}

// 4. 使用 flat 方法(ES2019)
function flattenByFlat(arr) {
    
    
  return arr.flat(Infinity);
}

// 5. 使用 toString 和 split 方法
function flattenByToString(arr) {
    
    
  return arr.toString().split(",").map(item => +item);
}

// 6. 使用正则表达式和 JSON 方法
function flattenByRegexAndJSON(arr) {
    
    
  return JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
}

// 7. 使用堆栈
function flattenByStack(arr) {
    
    
  let result = [];
  let stack = [...arr];
  
  while (stack.length) {
    
    
    let next = stack.pop();
    if (Array.isArray(next)) {
    
    
      stack.push(...next);
    } else {
    
    
      result.unshift(next);
    }
  }
  
  return result;
}

// 8. 使用扩展运算符和递归
function flattenBySpreadOperatorAndRecursion(arr) {
    
    
  return arr.reduce((acc, cur) => {
    
    
    return Array.isArray(cur) ? [...acc, ...flattenBySpreadOperatorAndRecursion(cur)] : [...acc, cur];
  }, []);
}

// 调用示例
let nestedArray = [1, [2, [3, 4], 5], 6, [7]];
console.log(flattenByRecursion(nestedArray));
console.log(flattenByReduce(nestedArray));
console.log(flattenBySpreadOperator(nestedArray));
console.log(flattenByFlat(nestedArray));
console.log(flattenByToString(nestedArray));
console.log(flattenByRegexAndJSON(nestedArray));
console.log(flattenByStack(nestedArray));
console.log(flattenBySpreadOperatorAndRecursion(nestedArray));

You can choose one of the methods to call according to your needs, or modify and optimize according to your specific needs.

おすすめ

転載: blog.csdn.net/ACCPluzhiqi/article/details/132136774