Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nest each element of an array

I need my array of
const arr = [a, b, c, d, e, f]
to be nested, more specifically, every element to be so.
Meaning my desired effect is for the array to looks like this arr = [[a], [b], [c], [d], [e], [f]]

For the opposite of what I want to achieve, I could use arr.flat(), but that’s not the case here. So I’m looking for answers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You want to perform something for every element of an array (in particular wrapping it inside another array). For performing an operation on every element of an array you can use Array.map().

const arr = [1, 2, 3];
const newArr = arr.map(item => [item]);
// newArr is [[1], [2], [3]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading