1

I have an array of numbers like

[1, 10, 100]  

The question is: how can I extract numbers from this array and transform these numbers into new, single-element arrays like

[1], [10], [100]    

Thank you.

4 Answers 4

1

You could use a destructuring assignment while mapping the arrays.

var [a, b, c] = [1, 10, 100].map(v => [v]);

console.log(a);
console.log(b);
console.log(c);

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

Comments

1

You can use Array#map function to map each item into a separate array. And if you know the count and want to keep them into separate variables, you can use array destructuring.

const singleItemArray = [1, 10, 100].map(item => [item]);

console.log(singleItemArray); // Array of single item arrays

const [first, second, third] = singleItemArray; // Destructuring the array of arrays into single arrays

console.log(`first: ${first}`);
console.log(`second: ${second}`);
console.log(`third: ${third}`);

Comments

0

how can I extract numbers from this array and transform these numbers into new, single-element arrays like [1], [10], [100]

Simply use map to return the item wrapped in an array and finally return a new array having every item as single item array.

arr.map(s=>[s])

Demo

console.log([1, 10, 100].map(s=>[s]))

Comments

0

Simple ES5 answer: oldArray.map(function(item) { return [item]; });;

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.