如何从数组列表创建多维数组/数组树?

时间:2016-06-01 16:42:11

标签: javascript arrays multidimensional-array

我有一个数组:

["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"]

任务是在一个数组中组成10个字符长度的数组,在这种情况下将是这样的:

[
  ["Lorem", "Ipsum"],
  ["Colo", "sit", "ame"], 
  ["consecteur"]
]

我试着这样做:

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var combArr = [];
var charCount = 0;

for (i = 0; i < arr.length; i++) {
    charCount += arr[i].length;
    if (charCount <= 10) {
        combArr.push(arr[i]);
    }
    if (charCount > 10 && charCount <= 20) {
        combArr.push(arr[i]);
    }
    // ...
}   

但是之后它会将它推回到与以前相同的顺序,因为我只推动每次通过条件的迭代。我不知道如何制作如上所述的多维数组。任何帮助,将不胜感激。谢谢!

6 个答案:

答案 0 :(得分:1)

以下是您的代码的更正版本:

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var combArr = [];
var charCount = 0;
var currArr = []; // ADDED: the current list of words 

for (i = 0; i < arr.length; i++) {
    if (charCount && (charCount + arr[i].length > 10)) {
        // save list
        combArr.push(currArr);
        // ... and start new list
        currArr = [];
        charCount = 0;
     }
     charCount += arr[i].length;
     currArr.push(arr[i]);
}   
// finally add remaining list to result:
combArr.push(currArr);

答案 1 :(得分:1)

你最不想要的东西;您需要创建 new 数组,然后将这些多个数组推送到父数组中。

一个例子,让你去;

var container = [];
var child1 = [];
var child2 = [];

child1.push("foo");
child1.push("bar");

child2.push("baz");

container.push(child1);
container.push(child2);

console.log(container); // [["foo", "bar"], ["baz"]]

我会把问题的条件逻辑留给你,但这应该让你超越这个障碍。祝你好运!

答案 2 :(得分:0)

试试这个; (编辑)的

&#13;
&#13;
 var arr = ["1234567890","hidden","para","meter"];
    var results= [];
    var charCount = 0;
    var temp=[];
    for (var i = 0; i < arr.length; i++) {
      charCount += arr[i].length;
        if(charCount>10){
          results.push(temp);
          charCount=arr[i].length;
          temp=[arr[i]];
        }else{
          temp.push(arr[i]);
        }
    }
    if(temp.length){results.push(temp);}
    document.write(JSON.stringify(results))
&#13;
&#13;
&#13;

试试这个;

&#13;
&#13;
var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var results= [];
var charCount = 0;

for (var i = 0,temp=[]; i < arr.length; i++) {
    if((charCount += arr[i].length)>=10){
      temp.push(arr[i]);
      results.push(temp);
      charCount=0;
      temp=[];
    }else{
      temp.push(arr[i]);
    }
}
document.write(JSON.stringify(results))
&#13;
&#13;
&#13;

答案 3 :(得分:0)

你可以尝试这样的事情。

var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var MAX_LENGTH = 10;
var finalArray = arr.reduce(function(prev, curr) {
  if (prev.length === 0) {
    prev.push([curr]);
  } else {
    var currentItemLength = prev[prev.length-1].reduce(function(iprev, icurr) {
      return iprev + icurr.length;
    }, 0);
    if (currentItemLength + curr.length > MAX_LENGTH) {
      prev.push([curr]);
    } else {
      prev[prev.length-1].push(curr);
    }
  }
  return prev;
}, []);
console.log(finalArray)

答案 4 :(得分:0)

您可以通过向combArr添加一个级别的嵌套来修复代码,为每个新的&#39;行重置charCount。并通过将arr附加到您的if条件来处理|| i == 0的第一个条目超过10个字符时的情况:

&#13;
&#13;
var arr = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
var combArr = [[]];
var charCount = 0;

for (i = 0; i < arr.length; i++) {
    charCount += arr[i].length;
    if (charCount <= 10 || i == 0) {
        combArr[combArr.length-1].push(arr[i]);
    } else {
        charCount = arr[i].length;
        combArr.push([arr[i]]);
    }
}

console.log(combArr);
&#13;
&#13;
&#13;

更高效的解决方案是:

&#13;
&#13;
function format(array, chars) {
  var result = [], chars = 0, prev = 0, length = array.length;
  for (var i = 0; i < length; ++i) {
    chars += array[i].length;
    if (i && chars > 10) {
      result.push(array.slice(prev, i));
      chars = array[i].length;
      prev = i;
    }
  }
  result.push(array.slice(prev, length));
  return result;
}

console.log(format(["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"]));
console.log(format(["12345678901", "", "1234567890", "", "1"]));
&#13;
&#13;
&#13;

答案 5 :(得分:0)

此解决方案不适合:

  1. 输入数组的顺序不正确,以确保完全配对10个字符,例如它不适用于[“hello”,“whatever”]的输入数组。
  2. 它不支持将数组项条件分割为两个单独的数组。 例如[“hello”,“whatever”] = [[“hello”,“whate”],[“ver”]]
  3. 因此,根据提供的信息,您可以尝试:

    var inputArray = ["Lorem", "Ipsum", "Colo", "sit", "ame", "consecteur"];
        var tempArray = [];
        var finalArray = [];
        var charCount = 0;
    
        for (i = 0; i < inputArray.length; i++) {
    
            if ((charCount + inputArray[i].length) <= 10) {
    
                charCount += inputArray[i].length;
    
                tempArray.push(inputArray[i]);
    
                if (charCount == 10) {
                    finalArray.push(tempArray);
                    tempArray = [];
                    charCount = 0;
                }
            }
        }
    
        //push whatever remains is in tempArray to the final array.
        if (tempArray.length)
            finalArray.push(tempArray);
    
        document.write(JSON.stringify(finalArray))