Is there an easy way to make nested array flat?

后端 未结 12 1557
执笔经年
执笔经年 2020-12-29 09:42

That is to make this:

[ [\'dog\',\'cat\', [\'chicken\', \'bear\'] ],[\'mouse\',\'horse\'] ]

into:

[\'dog\',\'cat\',\'chicken\',\'

12条回答
  •  轮回少年
    2020-12-29 10:35

    This solution has been working great for me, and i find it particularly easy to follow:

    function flattenArray(arr) {
      // the new flattened array
      var newArr = [];
    
      // recursive function
      function flatten(arr, newArr) {
        // go through array
        for (var i = 0; i < arr.length; i++) {
          // if element i of the current array is a non-array value push it
          if (Array.isArray(arr[i]) === false) {
            newArr.push(arr[i]);
          }
          // else the element is an array, so unwrap it
          else {
            flatten(arr[i], newArr);
          }
        }
      }
    
      flatten(arr, newArr);
    
      return newArr;
    }
    

提交回复
热议问题