簡體   English   中英

如何使這個數組展平函數在JavaScript中以遞歸方式運行?

[英]How do I make this array flattening function behave recursively in JavaScript?

此函數將僅將兩個級別的數組展平。

function arrFlattener(arr){
  var newarr = [];
  for(var i = 0; i < arr.length; i++){
    var target = arr[i];
      if(Array.isArray(target)){
        for(var j = 0; j < target.length; j++){
          if(Array.isArray(target[j])){
              for(var k = 0; k < target[j].length; k++){
                newarr.push(target[j][k]);
              }
          } else {
            newarr.push(target[j]);   
          }  
        }
      } else {
         newarr.push(arr[i]);
      }
   }
     return newarr;
}

arrFlattener([1, 2, 3, [4, 5, [6],[7],[8]]]); // returns [1, 2, 3, 4, 5, 6, 7, 8];

顯然,我需要一個遞歸函數。 在偽代碼中,我想象一個while循環,它將一直運行,直到它在當前數組中找不到嵌套數組。

任何幫助將不勝感激!

您可以在檢查isArray之后立即調用該函數,然后將分配的結果分配給newarr ,因為您可能需要多個元素。

基本上,您將下一次迭代留給函數調用,而不是迭代子數組。 這消除了所有其他后續循環(在舊函數中),因為它們在函數本身中完成,只有一個循環和必要時的遞歸調用。

 function arrFlattener(arr) { var newarr = []; for (var i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { newarr = newarr.concat(arrFlattener(arr[i])); // get the result of the recusion } else { newarr.push(arr[i]); } } return newarr; } console.log(arrFlattener([1, 2, 3, [4, 5, [6], [7], [8]]])); // returns [1, 2, 3, 4, 5, 6, 7, 8]; 

一個簡單的ES6解決方案就像是

function flatten(arr) {
    const out = [];  // Stores the flattened output; modified by `walk`.
    function walk(arr) {
        arr.forEach((val) => {  // Iterate through `arr`;
            if(Array.isArray(val)) walk(val);  // if the value is an array, call `walk`,
            else out.push(val);  // and otherwise just push the value to `out`.
        });
    }
    walk(arr);
    return out;
}

console.log(flatten([1, 2, 3, [4, 5, [6],[7],[8]]]));

輸出是,根據需要,

[ 1, 2, 3, 4, 5, 6, 7, 8 ]

以下解決方案基於遞歸工作的Array.reduce方法,並且也確認arguments數組...

 var array_flatten = (function (Array, Object) { "use strict"; var array_prototype_slice = Array.prototype.slice, expose_internal_class = Object.prototype.toString, isArguments = function (type) { return !!type && (/^\\[object\\s+Arguments\\]$/).test(expose_internal_class.call(type)); }, isArray = ((typeof Array.isArray == "function") && Array.isArray) || function (type) { return !!type && (/^\\[object\\s+Array\\]$/).test(expose_internal_class.call(type)); }, array_from = ((typeof Array.from == "function") && Array.from) || function (listAlike) { return array_prototype_slice.call(listAlike); }; return function flatten (list) { list = (isArguments(list) && array_from(list)) || list; if (isArray(list)) { list = list.reduce(function (collector, elm) { return collector.concat(flatten(elm)); }, []); } return list; }; }(Array, Object)); console.log(array_flatten([1, 2, 3, [4, 5, [6], [7], [8]]])); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM