How to convert a string to an array that takes the elements and combines them after each element?

Viewed 55

So if i have a string that looks like this:

const name = "Matt"

And want to create an array that looks like this:

nameSearchArr = [
0: "M",
1: 'Ma',
2: 'Mat',
3: 'Matt
]

I am trying to get around Firestores no 'full text search' problem by creating an array and using 'array-contains' so i can search a name and while typing in it will match the nameSearchArr. Anyone know the best way to do it? Thank you in advance!

2 Answers

Using slice is an elegant approach.

const getStringParts = (word) => {
   const result = [];
   for (let i = 1; i <= word.length; i++) {
      result.push(word.slice(0, i));
   }
   return result;
}

const name = "Matt";
console.log(getStringParts(name));

While I doubt this is overall a good solution for the 'full text search' problem, following code could do the trick:

const name = "Matt"

const result = name.split("").map((e, i) => name.slice(0,i+1))

console.log(result)

Related