/**
* Let us create a function that receives a string "abcbdbd",
* and returns an array like:
["a", "a.b", "a.b.c", "a.b.c.b", "a.b.c.b.d", "a.b.c.b.d.b", ...]
*/
function splitString(str) {
const arr = [];
for (var i = 0; i < str.length; i++) {
arr.push(str[i]);
for (var z = 0; z < arr.length; z++) {
const joinArr = `${arr[0]}.${arr[z]}`;
console.log(joinArr);
}
}
return [];
}
console.log(splitString("abcdebfkjj"));
how to add . after every string? I have tried for loop. So should I use map and .join?
An example using map
const str = "abcbdef";
const array = str.split("");
const output = array.map((_, idx, arr) => arr.slice(0, idx + 1).join("."));
console.log(output);
Create an array from the string (Array.from()), reduce it to an array, so that each element is the current last element (acc[acc.length-1]) in the array plus itself. For the first element just add it to the array.
function splitString(str) {
return Array.from(str).reduce((acc,cv) => {
if (acc[0]) acc.push(acc[acc.length-1]+"."+cv)
else acc[0] = cv // if the array is empty, add just the first char
return acc
},[])
}
console.log(splitString("abcdebfkjj"));
You could create an array of all characters and add the last returned value.
function splitString(str) {
return Array.from(
str,
(l => v => l += (l && '.') + v)('')
);
}
console.log(splitString("abcdebfkjj"));