将数组转换为多维数组?使用Javascript

时间:2017-07-05 23:23:36

标签: javascript arrays multidimensional-array

我正在努力创建一个简单的函数,它将采用像

这样的数组
["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]

并将其转换为多维数组,看起来像这样

[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]

基本上索引0和1合并为一个新的子数组然后2和3合并,依此类推...

我正在尝试循环,我增加了+2,但我不能正确,我认为这将是一个简单的解决方案,但我到目前为止所做的循环几乎崩溃了我的浏览器......任何帮助不胜感激。感谢

编辑:WOW感谢所有快速回复!我看了一切,学到了很多东西!

6 个答案:

答案 0 :(得分:1)

希望这会有所帮助......

我添加了一些评论,但随时可以询问您是否需要更多解释。

肯定有更先进(也更简短!)的方法,但在我看来,这是最直观,最容易理解的。

现在,如果元素数量奇怪,最后一个元素最终会被定义为#34;未定义。"如果您不希望以不同的方式工作,请与我们联系。



var array = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];

function combineTwo(inputArray) {
//Starting with the beginning of the array, this function combines index 0 with 1, 2 with 3, and so on for the entire length of the array
  var result = []; //this will the variable that we store our result in
  for (var i = 0; i < inputArray.length; i+=2) {
    //This for loop iterates through every other index of the array... for example: 0, 2, 4, etc.
    result.push([inputArray[i], inputArray[i+1]]); //Adds i and i+1 as a new array to the result array
  }
  return result;
}

console.log(combineTwo(array));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用 @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector") Array#reduce()&amp; Array#concat()

&#13;
&#13;
Array#slice()
&#13;
&#13;
&#13;

答案 2 :(得分:0)

有很多方法可以做到这一点。在这里,我们使用 this MSDN article 方法将项目返回到新数组中,然后使用 Array.map() 清除所有undefined元素

&#13;
&#13;
var startArray = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];

// Create a new array by iterating the first one...
var resultArray = startArray.map(function(item, index, arry){
  // If we are on an even index...
  if(index % 2 === 0){
    // Send the item and the one that follows it into the new array
    return [item, arry[index + 1]];
  }
});

// The resulting array will contain undefined for each enumeration that didn't 
// return anything, so we can clean that up by filtering out the undefined elements
resultArray = resultArray.filter(function( element ) {
   return element !== undefined;
});

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

然而,似乎你想要将一系列成分和成分结合起来制作最终产品,因此创建object会更合适,因为对象实际上只不过是键/值的分组如果您打算进行OOP操作,可以使用更多功能。这里的结果是一个配方对象数组:

&#13;
&#13;
// Create a new array that will store recipe objects
var cookbook = [];

function addRecipeToCookbook(ary){
  // Create a "recipe" object
  var recipe = {};
 
  // Iterate the passed array...
  ary.forEach(function(item, index, array){
    // If we are on an even index...
    if(index % 2 === 0){
      // Add the item as a new property of the recipe object with the quantity as the value
      recipe[item] = array[index + 1];    
    }
  });

  // Add the object to the new array
  cookbook.push(recipe);
}

// Now you can add as many recipies as you like:
var recipeArray1 = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];
var recipeArray2 = ["pork","2 lbs","BBQ sauce","2 cups","onion","3 ounces"];
var recipeArray3 = ["beef","5 lbs","worchestishire sauce","4 ounces","garlic","1 clove"];

// Just call the reusable function and pass a recipe array:
addRecipeToCookbook(recipeArray1);
addRecipeToCookbook(recipeArray2);
addRecipeToCookbook(recipeArray3);

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

答案 3 :(得分:0)

使用.reduce()执行此操作的另一种方法是:

&#13;
&#13;
var array = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];

var array2d = array.reduce((array, element, index) => {
  if (index % 2 > 0) {
    array.push(array.pop().concat([element]));
  } else {
    array.push([element]);
  }
  
  return array;
}, []);

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

可以使用的更通用的方法可能如下所示:

&#13;
&#13;
function group(amount) {
  return (array) => array
    .reduce((array, element, index) => {
      if (index % amount > 0) {
        array.push(array.pop().concat([element]));
      } else {
        array.push([element]);
      }
      
      return array;
    }, []);
}

var a = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];
var b = ["chicken","10","lbs","hot sauce","4","cups","celery","1","stalk"];
var group2 = group(2);
var group3 = group(3);
var a2d = group2(a);
var b2d = group3(b);

console.log(a2d);
console.log(b2d);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

另一种选择是接受第二个参数,该参数决定了每个子阵列中你想要多少项。例如:

function squash(arr, num) {
 let results = [];
 let start, end;

 for (let i = 1; i < arr.length; i++) {
  start = (i - 1) * num;
  end = i * num;

  let sliced = arr.slice(start, end);

  if (start >= arr.length) { // need to make sure we don't go passed the end
   break;
  }

  results.push(sliced);
 }
 return results;
}

答案 5 :(得分:0)

对我来说最直观,只需将原始数组中的项目移除,直到它为空:

    let array = ["chicken", "10 lbs", "hot sauce", "4 cups", "celery", "1 stalk"],
        newArray = [];
    while (array.length) {
        newArray.push([array.shift(), array.shift()]);
    }
    console.log(newArray);