Home > Web Front-end > JS Tutorial > body text

All ways to divide a string array into parts in JavaScript

WBOY
Release: 2023-09-21 18:45:03
forward
816 people have browsed it

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)"
Copy after login

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));
Copy after login

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; ]
]
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template