arrays - JavaScript: Convert [a,b,c] into [a][b][c] - Stack Overflow

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

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 an Array: [a]. Index that array with the value b. Index that value with the value c." 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
Add a ment  | 

4 Answers 4

Reset to default 9

You 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;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742183732a4397321.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信