Home  >  Article  >  Web Front-end  >  All ways to divide a string array into parts in JavaScript

All ways to divide a string array into parts in JavaScript

WBOY
WBOYforward
2023-09-21 18:45:03773browse

JavaScript 中将字符串数组划分为多个部分的所有方法

Question

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

Example

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

Output

[
[ &#39;az&#39;, &#39;toto picaro zone kiwi&#39; ],
[ &#39;az toto&#39;, &#39;picaro zone kiwi&#39; ],
[ &#39;az toto picaro&#39;, &#39;zone kiwi&#39; ],
[ &#39;az toto picaro zone&#39;, &#39;kiwi&#39; ]
]

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete