最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论