Skip to content

Array from number JavaScript | Example code

  • by

Using the Array from() Method or map() method, you can get an Array from the number in JavaScript. The JavaScript Array from() method returns an Array object from any object with a length property or an iterable object.

Array.from(object, mapFunction, thisValue)

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array.

array.map(function(currentValue, index, arr), thisValue)

Array from number JavaScript

Simple example code.

Using Array.from() Method:

<!DOCTYPE html>
<html>
<body>
  <script>
   var num = 123456;

   let myFunc = num => Number(num);
   var intArr = Array.from(String(num), myFunc);

   console.log(intArr);

 </script>
</body>
</html>

Output:

Array from number JavaScript

Using map() Method:

<script>
   var num = 123456;

   var myArr = String(num).split("").map((num)=>{
    return Number(num)
  })
   console.log(myArr)// [ 1, 2, 3, 4, 5, 6 ]
</script>

Take an array of numbers and return an array with numbers doubled using the array map method.

const numbers = [1, 2, 3];

function doubleNumbers(numbers) {
    return numbers.map(x => x * 2);
}

console.log(doubleNumbers(numbers));

Output: [ 2, 4, 6 ]

Create an array sequence from 1 to N in a single line in JavaScript

const N = 5;
const arr = Array.from({length: N}, (_, index) => index + 1);
console.log(arr);// [ 1, 2, 3, 4, 5 ]

Do comment if you have any doubts or suggestions on this Js Array code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading