C3PO
C3PO

Reputation: 13

I have a question about .map to bring elements in the array into an array with javascript

I am currently trying to bring the elements in an array into other arrays in the array. I have now read that .map works well and have found newArrayA as an example. Can't I just leave out the dots and just do it as in newArrayB? Does anyone have anything else to read? I can find almost nothing on this example. Is there anything that speaks against newArrayB?

let test = ['A', 'B', 'C', 'D']; // to [ [ 'A' ], [ 'B' ], [ 'C' ], [ 'D' ] ]

newArrayA = test.map((x) => [...x]);
newArrayB = test.map((x) => [x]);

console.log(newArrayA);
console.log(newArrayB);

Upvotes: 0

Views: 41

Answers (1)

Thomas Kuhlmann
Thomas Kuhlmann

Reputation: 1003

You can see the difference by increasing the length of one of the strings - you get different results when you use the spread operator vs simply using the value at an index - just run this example:

let test = ['ABCDE', 'B'];  

newArrayA = test.map((x) => [...x]);
newArrayB = test.map((x) => [x]);

console.log(newArrayA);
console.log(newArrayB);

Upvotes: 1

Related Questions