Creating an array for search purposes based on a string like BBC Sport
, the desired output array will be:
[ 'BBC', 'BB', 'B', 'Sport', 'Spor', 'Spo', 'Sp', 'S' ]
An implementation using 2 for loops is as follows:
const s = "BBC sport";
const tags = [];
const words = s.split(" ");
for (let word of words) {
const wl = word.length;
for (let i = 0; i < wl; i++) {
tags.push(word.substr(0, wl - i));
}
}
// tags now equals [ 'BBC', 'BB', 'B', 'Sport', 'Spor', 'Spo', 'Sp', 'S' ]
However, there is a desire to achieve the same outcome using the reduce function instead of for loops.
If you were to solve this problem, how would you do it?