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
Divide a string into n equal parts - JavaScript
We are required to write a JavaScript function that takes in a string and a number n (such that n exactly divides the length of string). We need to return an array of string of length n containing n equal parts of the string.
Let's write the code for this function ?
Example
const str = 'this is a sample string';
const num = 5;
const divideEqual = (str, num) => {
const len = str.length / num;
const creds = str.split("").reduce((acc, val) => {
let { res, currInd } = acc;
if(!res[currInd] || res[currInd].length < len){
res[currInd] = (res[currInd] || "") + val;
}else{
res[++currInd] = val;
};
return { res, currInd };
}, {
res: [],
currInd: 0
});
return creds.res;
};
console.log(divideEqual(str, num));
Output
Following is the output in the console ?
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]
Simpler Approach Using Substring
Here's a more straightforward solution using the substring() method:
const divideEqualSimple = (str, num) => {
const partLength = str.length / num;
const result = [];
for (let i = 0; i < num; i++) {
const start = i * partLength;
const end = start + partLength;
result.push(str.substring(start, end));
}
return result;
};
const str = 'this is a sample string';
const num = 5;
console.log(divideEqualSimple(str, num));
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]
How It Works
Both approaches divide the string length by the number of parts to get the length of each part. The first method uses reduce() to build the array character by character, while the second uses substring() to extract parts directly based on calculated positions.
Conclusion
The substring approach is more readable and efficient for dividing strings into equal parts. Both methods work correctly when the string length is exactly divisible by n.
