I have arrays like [a]
, [a,b]
, [a,b,c]
and so on.
How can I convert them into [a]
, [a][b]
, [a][b][c]
and so on?
Example:
var arr = [1,2,3,4];
arr = do(arr); // arr = arr[1][2][3][4]
I have arrays like [a]
, [a,b]
, [a,b,c]
and so on.
How can I convert them into [a]
, [a][b]
, [a][b][c]
and so on?
Example:
var arr = [1,2,3,4];
arr = do(arr); // arr = arr[1][2][3][4]
Share
Improve this question
asked Jul 20, 2016 at 11:09
VahidVahid
3,4424 gold badges36 silver badges71 bronze badges
2
-
The expression
[a][b][c]
means, "Create anArray
:[a]
. Index that array with the valueb
. Index that value with the valuec
." Is that what you want to acplish? – A. Vidor Commented Jul 20, 2016 at 11:17 - @this-vidor I mean 3D, 4D, ... array if you mean that. – Vahid Commented Jul 20, 2016 at 11:27
4 Answers
Reset to default 9You could map it with Array#map
.That returns an array with the processed values.
ES6
console.log([1, 2, 3, 4].map(a => [a]));
ES5
console.log([1, 2, 3, 4].map(function (a) {
return [a];
}));
While the question is a bit unclear, and I think the OP needs possibly a string in the wanted form, then this would do it.
console.log([1, 2, 3, 4].reduce(function (r, a) {
return r + '[' + a + ']';
}, 'arr'));
Functional:
use .map
like this
[1,2,3,4].map(i => [i])
Iterative:
var list = [1, 2, 3, 4], result = [];
for (var i=0; i<list.length; i++) {
result.push([list[i]]);
}
If I understand you correctly, you are converting single dimension array to multi dimensional array. To do so,
var inputArray = [1,2,3,4];
var outputArray = [];
for(var i=0;i<inputArray.length;i++)
{
outputArray.push([inputArray[i]])
}
function map(arr){
var aux = [];
for(var i=0; i<arr.length;++i){
var aux2 = [];
aux2.push(arr[i]);
aux.push(aux2);
}
return aux;
}