0

How can I convert the elements of the array into another array?

let a = [2, 4, 0, 8, 9, 15]

and the result will be :

a = [[2], [4], [0], [8], [9], [15]]

3 Answers 3

7

Use Array#map to iterate the array, and wrap each item in an array:

let a = [2, 4, 0, 8, 9, 15]

const result = a.map((n) => [n])

console.log(JSON.stringify(result))

Sign up to request clarification or add additional context in comments.

6 Comments

What type of nomenclature is "Array#map" supposed to be?
It's an old MDN way of naming methods, which you can paste to the location box in the browser, and it will find the article in mdn, instead of trying to get to the website.
What benefit does it have today?
Mainly me being used to it :)
You might be used to it, but you're educating others here.
|
1
let a = [2, 4, 0, 8, 9, 15];
let b = a.map((item) => [item]);

Comments

1
    a = [2, 4, 0, 8, 9, 15]
    console.log(result = a.map((n) => [n]))
    b=[]
//you can try  below also
     for (i in a){
      b.push([i]);
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.