1

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' ] ]

0

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This works great, however if the array is larger such as: [['apple', 'green'], ['banana', 'yellow'], ['cherry', 'red']] the second value gets truncated and replaced with 'name' instead of being appended to the end of each sub-array.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.