- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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' ] ]
Advertisements