0

Let's assume I have four existing arrays:

var one =   ["apple","banana","berry"];
var two =   ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four =  ["seven", "eight", "eleven"];

How would I merge them into one array and return it in the most simple way? What I got is

var result = [one, two, three, four];

resulting in

|-----------------------------|
|  apple  |  banana  | berry  |  
|  foobar |  barfoo  | farboo |  
|  13     |  421     |        |
|  seven  |  eight   | eleven |
|-----------------------------|

However, what I actually need is this:

|------------------------------------|
|  apple  |  foobar  | 13  |  seven  |
|  banana |  barfoo  | 421 |  eight  |
|  berry  |  farboo  |     |  eleven |
|------------------------------------|
1
  • 3
    Warning to those answering: Google Apps Script is roughly ES3 (yes, 3) plus some standard library features from ES5. (I hear there's an update in the works, though.) Commented Apr 12, 2019 at 14:24

2 Answers 2

1

Try

var output = one.map(function(e,i){
  return [e].concat([two, three, four].map(function(f){
    return f[i] === undefined ? '': f[i];
  }))
})
console.info(output);
Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript doesn't have multi-dimensional arrays, it has arrays of arrays.

If you don't already have the one, two, three, four arrays, you can do it with a single nested literal:

var result = [
    ["apple", "fobar", 13, "seven"],
    ["banana", "barfoo", 421, "eight"],
    ["berry", undefined, "eleven"]
];

Live Example:

var result = [
    ["apple", "fobar", 13, "seven"],
    ["banana", "barfoo", 421, "eight"],
    ["berry", "farboo", undefined, "eleven"]
];
console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
}

If you do already have them, since they're arrays of column values and apparently you want the subarrays to be row values, you need to loop:

var result = [];
for (var i = 0; i < 3; ++i) {
    result[i] = [
        one[i], two[i], three[i], four[i]
    ];
}

Live Example:

var one =   ["apple","banana","berry"];
var two =   ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four =  ["seven", "eight", "eleven"];
var result = [];
for (var i = 0; i < 3; ++i) {
    result[i] = [
        one[i], two[i], three[i], four[i]
    ];
}
console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
}

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.