
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split JavaScript String by Given Array Element
Let’s say, we are given a string and an array. Our job is to split the string according to the corresponding elements of the array. For example −
Input
const string = 'Javascript splitting string by given array element'; const arr = [2, 4, 5, 1, 3, 1, 2, 3, 7, 2];
Output
['Ja','vasc','ript ','s','pli','t','ti','ng ','string ','by']
Let’s write a function, say splitAtPosition that takes in the string and the array and makes use of the Array.Prototype.reduce() method to return the splitted array.
The code for this function will be −
Example
const string = 'Javascript splitting string by given array element'; const arr = [2, 4, 5, 1, 3, 1, 2, 3, 7, 2]; const splitAtPosition = (str, arr) => { const newString = arr.reduce((acc, val) => { return { start: acc.start + val, newArr: acc.newArr.concat(str.substr(acc.start, val)) } }, { start: 0, newArr: [] }); return newString.newArr; }; console.log(splitAtPosition(string, arr));
Output
The output in the console will be −
[ 'Ja', 'vasc', 'ript ', 's', 'pli', 't', 'ti', 'ng ', 'string ', 'by' ]
Advertisements