Reputation:
I have the array range
with 3 columns and 10 rows.
How can I concatenate the contents of column 1 with column 2 and push them to a new range dataEnome
?
I'm using the following loop, but it isn't very efficient:
var dataEnome =[];
for (i=0; i<range.length; i++){
dataEnome.push(range[i][0])+(range[i][1]);
};
Upvotes: 1
Views: 6981
Reputation: 13356
... besides dataEnome.push(range[i][0])+(range[i][1]);
does most probably feature a broken syntax ...
shouldn't it be dataEnome.push(range[i][0] + range[i][1]);
or dataEnome.push(range[i][0].concat(range[i][1]));
... I do not consider the OP's solution to be not that efficient.
One only could transform it into a reusable and more functional style ...
function collectConcatenatedFirstTwoRowColumns(collector, row) {
collector.push(row[0].concat(" / ", row[1]));
return collector;
}
var
range = [
["0, 0", "0, 1", "0, 2"],
["1, 0", "1, 1", "1, 2"],
["2, 0", "2, 1", "2, 2"],
["3, 0", "3, 1", "3, 2"],
["4, 0", "4, 1", "4, 2"],
["5, 0", "5, 1", "5, 2"]
],
dataEnome = range.reduce(collectConcatenatedFirstTwoRowColumns, []);
console.log(dataEnome);
Upvotes: 0
Reputation: 129
If you want to concatenate each record from both column
You may do something like this:
var dataEnome =[];
for (i=0; i<range.getValues().length; i++){
dataEnome.push(range.getValues()[i][0]+range.getValues()[i][1]);
};
Hope this will help you.
Thanks.
Upvotes: 0
Reputation: 19228
For data mapping you can consider using the array.map
API.
Example:
var range =
[
[ 'col1.a', 'col2.1', 'c' ],
[ 'col1.b', 'col2.2', '3' ],
[ 'col1.c', 'col2.3', '6' ],
[ 'col1.d', 'col2.4', '9' ],
[ 'col1-e', 'col2.5', '1c' ],
[ 'col1-f', 'col2.6', '6c' ],
[ 'col1-g', 'col2.7', '7c' ],
[ 'col1-h', 'col2.8', '8c' ],
[ 'col1-i', 'col2.9', '9c' ],
[ 'col1-j', 'col2.10', '0c' ],
];
var dataEnome =range.map(row => { return row[0] + row[1]});
console.log(dataEnome);
For more example usages for map
;
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Upvotes: 1