Check if the word exists in the string using array of strings and separate the string in a new array

0

I'm in a problem where I want a string to become an array with the words separated, but 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 so:

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

Could anyone help me?

    
asked by anonymous 19.10.2017 / 15:35

0 answers