JavaScript Splitting 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'
]

Updated on: 20-Aug-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements