We need to write a JavaScript function that accepts a literal array with at least two elements.
Our function should return the array divided into two non-empty parts.
For example -
For the array ["az", "toto", "picaro", "zone", "kiwi" ]
the possibility is -
"(az, toto picaro zone kiwi)(az toto, picaro zone kiwi)(az toto picaro, zone kiwi)(az toto picaro zone, kiwi)"
The following is the code-
Real-time demonstration
const arr = ["az", "toto", "picaro", "zone", "kiwi"]; const findAllPossiblities = (arr = []) => { let array; const res = []; for(let i = 1; i < arr.length; i++){ array = []; array.push(arr.slice(0,i).join(" ")); array.push(arr.slice(i).join(" ")); res.push(array); }; return res; }; console.log(findAllPossiblities(arr));
[ [ 'az', 'toto picaro zone kiwi' ], [ 'az toto', 'picaro zone kiwi' ], [ 'az toto picaro', 'zone kiwi' ], [ 'az toto picaro zone', 'kiwi' ] ]
The above is the detailed content of All ways to divide a string array into parts in JavaScript. For more information, please follow other related articles on the PHP Chinese website!