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
Constructing an array of first n multiples of an input number in JavaScript
We are required to write a JavaScript function that takes in two numbers, let say m and n.
Our function should construct and return an array of first n natural multiples of m.
Problem Statement
Given two numbers m and n, we need to create a function that returns an array containing the first n multiples of m. For example, if m = 6 and n = 5, the function should return [6, 12, 18, 24, 30].
Method 1: Using a For Loop
The most straightforward approach is to use a for loop to iterate n times and multiply m by each iteration index:
const m = 6;
const n = 14;
const firstNMultiple = (m = 1, n = 1) => {
const res = [];
for(let i = 1; i
[6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84]
Method 2: Using Array.from()
A more functional approach using Array.from() with a mapping function:
const getMultiples = (m, n) => {
return Array.from({length: n}, (_, index) => m * (index + 1));
};
console.log(getMultiples(5, 8));
[5, 10, 15, 20, 25, 30, 35, 40]
Method 3: Using Array.fill() and map()
Another approach combining Array.fill() and map():
const createMultiples = (m, n) => {
return new Array(n).fill(0).map((_, i) => m * (i + 1));
};
console.log(createMultiples(3, 6));
[3, 6, 9, 12, 15, 18]
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| For Loop | High | Best | Efficient |
| Array.from() | High | Good | Efficient |
| Array.fill().map() | Medium | Fair | Less efficient |
Conclusion
The for loop approach offers the best performance and readability for generating arrays of multiples. Array.from() provides a more functional style while maintaining good performance. Choose based on your coding style preferences and performance requirements.
