I have an onedimensional array which I want to store in a multidimensional array. Here an example:
[RE-10032, 130.4, 09.08.2020, 31.08.2020, Bezahlt, RE-10033, 150.22, 01.09.2020, 30.09.2020, Offen, RE-10034, 111.3, 01.10.2020, 16.10.2020, Offen]
And out of this Array, I want to create a multidimensional one:
[[RE-10032, 130.4, 09.08.2020, 31.08.2020], [Bezahlt, RE-10033, 150.22, 01.09.2020, 30.09.2020, Offen], [RE-10034, 111.3, 01.10.2020, 16.10.2020, Offen]]
The length of the array is not fixed, therefore you can divide the array every time by 5. So this is what I came up with:
function ReceiveArray(values){
var storevalues = values;
var storevalueslength = storevalues.length +1;
var multiarray = [];
var x = 0;
var y = 0;
for (var i=0; i<storevalueslength; i++){
if( i % 5 == 0 && i > 0){
x++;
y = 0;
multiarray[[x][y]] = storevalues[i];
y++;
}
else{
multiarray[[x][y]] = storevalues[i];
y++;
}
}
Logger.log(multiarray);
}
My Idea was: Every time "i" is dividable by 5, x counts up and y is set to 0, so all of the following values get stored into the next array of the array. But for some reason, it is not working. I hope somebody has a solution :D
2 Answers 2
Using Array#slice() in a for loop makes it fairly easy.
The for loop increments by the desired length of the sub-arrays each iteration
const arr = ['RE-10032', 130.4, '09.08.2020', '31.08.2020', 'Bezahlt', 'RE-10033', 150.22, '01.09.2020', '30.09.2020', 'Offen', 'RE-10034', 111.3, '01.10.2020', '16.10.2020', 'Offen']
const res = [],
subLen = 5;
for (let i = 0; i < arr.length; i += subLen) {
res.push(arr.slice(i, i + subLen))
}
console.log(res)
Comments
The following code instantiates a new array result to contain the results and walks through the source array arr. The index to insert an item in the result array can be calculated by Math.floor(i / n). We create a sub-array at each index if one does not already exist, and push the current item into the subarray.
const arr = [
'RE-10032', 130.4, '09.08.2020', '31.08.2020', 'Bezahlt',
'RE-10033', 150.22, '01.09.2020', '30.09.2020', 'Offen',
'RE-10034', 111.3, '01.10.2020', '16.10.2020', 'Offen' ]
function group(arr, n = 5) {
const result = []
for (let i = 0; i < arr.length; i++) {
const j = Math.floor(i / n)
result[j] = result[j] || []
result[j].push(arr[i])
}
return result
}
console.log(group(arr))
Comments
Explore related questions
See similar questions with these tags.
modulooperations in JS developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/…