Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Array of multiples - JavaScript
We are required to write a JavaScript function that takes in two numbers, say m and n, and it returns an array of first n multiples of m.
For example ? If the numbers are 4 and 6
Then the output should be ?
const output = [4, 8, 12, 16, 20, 24]
Example
Following is the code ?
const num1 = 4;
const num2 = 6;
const multiples = (num1, num2) => {
const res = [];
for(let i = num1; i
Output
Following is the output in the console ?
[ 4, 8, 12, 16, 20, 24 ]
Alternative Method: Using Array.from()
We can also create the array of multiples using Array.from() with a mapping function:
const getMultiples = (m, n) => {
return Array.from({length: n}, (_, index) => m * (index + 1));
};
console.log(getMultiples(4, 6));
console.log(getMultiples(3, 5));
console.log(getMultiples(7, 4));
[ 4, 8, 12, 16, 20, 24 ]
[ 3, 6, 9, 12, 15 ]
[ 7, 14, 21, 28 ]
How It Works
The first approach uses a for loop that starts from m and increments by m in each iteration until it reaches m * n. The second approach creates an array of length n and maps each index to its corresponding multiple.
Conclusion
Both methods effectively generate arrays of multiples. The for loop approach is more explicit, while Array.from() provides a more functional programming style solution.
