最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Turning an array into a multidimensional array? Javascript - Stack Overflow

programmeradmin2浏览0评论

I am struggling to create a simple function that will taking an array such as

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

and turn it into a multidimensional array that looks like this

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

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT: WOW Thanks for all the rapid responses! I looked at everything and learned a lot!

I am struggling to create a simple function that will taking an array such as

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

and turn it into a multidimensional array that looks like this

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

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT: WOW Thanks for all the rapid responses! I looked at everything and learned a lot!

Share Improve this question edited Jul 6, 2017 at 0:10 benjaminadk asked Jul 5, 2017 at 23:23 benjaminadkbenjaminadk 4986 silver badges19 bronze badges 3
  • Is your original array dinamically generated? If so, what happens if the number of elements is odd? here is an example with your original array turning to multidimensional jsfiddle/lixusrarnavo/704kjhgf – Lixus Commented Jul 5, 2017 at 23:27
  • 1 Take a look at my updated answer. I think it is more in line with what you are trying to acplish. – Scott Marcus Commented Jul 5, 2017 at 23:55
  • @ScottMarcus I should have clarified. This array in question is just a small part of a Recipe Box project. This was just a small piece for when a user inputs for an ingredients list. The overall recipe has three keys, one of which is ingredients. And that recipe as a whole is an object, which in turn is inside a big array which is the recipe box, which goes into local storage. So yah its an array of objects. – benjaminadk Commented Jul 6, 2017 at 0:15
Add a ment  | 

6 Answers 6

Reset to default 3

Using Array#reduce(), Array#concat() & Array#slice()

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

var res = data.reduce((a, c, i) => {
  return i % 2 === 0 ? a.concat([data.slice(i, i + 2)]) : a;
}, []);


console.log(res)

Hope this helps...

I added some ments but feel free to ask if you need more explanation.

There are definitely more advanced (and much shorter!) ways of doing this, but this is the most intuitive and easiest to understand, in my opinion.

Right now, if there is an odd amount of elements, the last element will end up being "undefined." Let me know if you'd like this to work differently.

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

function bineTwo(inputArray) {
//Starting with the beginning of the array, this function bines 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(bineTwo(array));

There are many ways to do this. Here, we are using the Array.map() method to return items into a new array and then cleaning out any undefined elements using Array.filter().

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);

However, it seems that you want to make an array of ingredients and ingredients bine to make a final product, so creating an object would be more appropriate, since objects are really nothing more than groupings of key/value pairs and can be more versatile if you plan on doing OOP operations. The result here is an array of recipe objects:

// 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);

Another option is to take in a second argument that dictates how many items you would like in each subarray. For instance:

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;
}

Just another way to do this using .reduce():

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);

A more generic method that could be used might look like the following:

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);

most intuitive for me, just keep yanking items off the original array until it is empty:

    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);
发布评论

评论列表(0)

  1. 暂无评论