最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin9PV0评论

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far