हमें एक JavaScript फंक्शन लिखना है जो एक स्ट्रिंग और एक संख्या n लेता है (ऐसा कि n स्ट्रिंग की लंबाई को सटीक रूप से विभाजित करता है)। हमें लंबाई n के स्ट्रिंग का ऐरे लौटाना है जिसमें स्ट्रिंग के n बराबर भाग हों।
उदाहरण
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));
आउटपुट
कंसोल में निम्नलिखित आउटपुट है -
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]