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
Selected Reading
Cutting off number at each digit to construct an array in JavaScript
We need to write a JavaScript function that takes a number and returns an array of strings, where each string represents the number cut off at each digit position.
Problem
Given a number like 246, we want to create an array containing:
- First digit: "2"
- First two digits: "24"
- All digits: "246"
Example
Here's the implementation:
const num = 246;
const cutOffEach = (num = 1) => {
const str = String(num);
const res = [];
let temp = '';
for(let i = 0; i < str.length; i++){
const el = str[i];
temp += el;
res.push(temp);
};
return res;
};
console.log(cutOffEach(num));
[ '2', '24', '246' ]
How It Works
The function converts the number to a string, then iterates through each character, building progressively longer substrings:
// Step by step for num = 246:
const cutOffEach = (num = 1) => {
const str = String(num); // "246"
const res = [];
let temp = '';
// i=0: temp = "" + "2" = "2", push "2"
// i=1: temp = "2" + "4" = "24", push "24"
// i=2: temp = "24" + "6" = "246", push "246"
for(let i = 0; i < str.length; i++){
temp += str[i];
res.push(temp);
}
return res;
};
console.log(cutOffEach(1357));
console.log(cutOffEach(89));
[ '1', '13', '135', '1357' ] [ '8', '89' ]
Alternative Approach Using Substring
We can also use the substring() method:
const cutOffEachAlt = (num = 1) => {
const str = String(num);
const res = [];
for(let i = 1; i <= str.length; i++){
res.push(str.substring(0, i));
}
return res;
};
console.log(cutOffEachAlt(582));
[ '5', '58', '582' ]
Conclusion
Both approaches convert the number to a string and build an array of progressively longer substrings. The first method concatenates characters, while the second uses substring extraction.
Advertisements
