One question a day, keep thinking

Sometimes the members of an array are still an array, so if you want to flaten that array into a one-dimensional array, that’s what we’re going to do today.

The problem

Put the array: [1[6.7], [2[3[4]], 5[] becomes: [1.6.7.2.3.4.5]
Copy the code

The specific implementation

function flattenArr(array, result) {
  let index = -1./ / index value
      length = array.length; // The length of the current array

  result = result || [];

  while (++index < length) {
    let value = array[index];
    // Check whether each array member is an array
    if (Object.prototype.toString.call(value) === "[object Array]") {
      // Call recursively, passing the current array of members as an argument, as well as the result
      flattenArr(value, result);
    } else {
      // Add a member to the last bit of the new arrayresult[result.length] = value; }}return result;
}
Copy the code

Implementation approach

Parameters:

  1. array(Array) : Arrays to be flattened;
  2. result(Array) : Records each Array member;

The main idea of this method is to implement the idea that every recursive “beat flat” result is recorded in the array of result, and then through the implementation of the array of while traversal, Traversal process through the Object. The prototype. ToString. Call (value) = = = “[Object Array]” judge whether the current members of an Array, if the current members of the Array is of type Array, then the recursive calls to the method, If not, add the current array member to the end of the result array.

If you see something wrong or could be improved, feel free to comment. If you think it’s good or helpful, please like, comment, retweet and share. Thank you