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?