All ways to divide array of strings into parts in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of literals of at least two elements.

Our function should return all the ways to divide the array into two non-empty parts.

For instance −

For the array ["az", "toto", "picaro", "zone", "kiwi"]

The possibilities are −

"(az, toto picaro zone kiwi)(az toto, picaro zone kiwi)(az toto picaro, zone kiwi)(az toto picaro zone, kiwi)"

Example

Following is the code −

 Live Demo

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));

Output

[
[ 'az', 'toto picaro zone kiwi' ],
[ 'az toto', 'picaro zone kiwi' ],
[ 'az toto picaro', 'zone kiwi' ],
[ 'az toto picaro zone', 'kiwi' ]
]

Updated on: 20-Apr-2021

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements