Home > OS >  Adding values to 2D array with forEach
Adding values to 2D array with forEach

Time:11-05

I am trying to add values to a 2D array in Google Apps Script. The following code runs, but is not the desired output for the array.

function fruitList() {
  var fruitArray = [['apple'], ['banana'], ['cherry']];
  var newArray = [];

  fruitArray.forEach(function(value) {
    newArray.push([value, "name"]);
  });
}

My code yields the following output:

[ [ [ 'apple' ], 'name' ], [ [ 'banana' ], 'name' ], [ [ 'cherry' ], 'name' ] ]

My desired output is:

[ [ 'apple', 'name' ], [ 'banana', 'name' ], [ 'cherry', 'name' ] ]

CodePudding user response:

value is a array. Not a string/primitive value. You can use destructuring assignment to get the actual value:

fruitArray.forEach(function([/*destructure 1D array*/value]) {
  newArray.push([value, "name"]);
});

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ 
function fruitList() {
  var fruitArray = [['apple'], ['banana'], ['cherry']];
  var newArray = [];
  fruitArray.forEach(function([value]) {
    newArray.push([value, "name"]);
  });
  console.info(newArray)
}
fruitList()
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

CodePudding user response:

Add a value:

function fruitList() {
  var fruitArray = [['apple'], ['banana'], ['cherry']];
  var newArray = [];

  fruitArray.forEach(function(value) {
    newArray.push([value[0], "name"]);
  });
  Logger.log(JSON.stringify(newArray))
}

Execution log
3:27:33 PM  Notice  Execution started
3:27:34 PM  Info    [["apple","name"],["banana","name"],["cherry","name"]]
3:27:34 PM  Notice  Execution completed
  • Related