Check for the word in the string using string array and separate the string in a new array

Asked

Viewed 149 times

0

I’m in a problem where I want a string to become an array with separate words, only the code returns duplicate arrays

    var string = 'xicara,cafecafe';
    var array1 = ['casa', 'xicara', 'xicarada', 'xicrinha', 'xi', 'carro', 'cafe', ',', 'ca'];
    function extrair(str, arr) {
        var encontradas = [];
        for (var i = 0; i < str.length; i++) {
            arr.forEach(function (match, index) {
                if (str.slice(i).indexOf(match) == 0) {
                    encontradas.push(match);
                };
            });
        }
        return encontradas;
    }
    var array2 = extrair(string, array1);
    console.log(array2); //  ["xicara", "xi", "ca", ",", "cafe", "ca"];

I wanted the array2 to have the same values as the string, like this:

console.log(array2); //  ['xicara', ',', 'cafe', 'cafe'];

Could someone help me?

  • 2

    How was I supposed to know cafecafe are two words? Just do it this way to interpret the other way, starting from the array of Matches, traversing and doing indexOf in var string, but potentially brings other problems

  • then there is no way to make the output ['xicara', ',', 'cafe', 'cafe']; instead of ["xicara", "xi", "ca", ",", "cafe", "ca", "cafe", "cafe", "ca""]?

  • 1

    The problem and solution is in the way 'xicara,cafecafe' was built and not in the algorithm presented in the question. There has to be a unique way to identegrate every word/token in that string otherwise it will not be possible

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.