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?
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 doingindexOf
invar string
, but potentially brings other problems– Isac
then there is no way to make the output ['xicara', ',', 'cafe', 'cafe']; instead of ["xicara", "xi", "ca", ",", "cafe", "ca", "cafe", "cafe", "ca""]?
– Adry
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– Isac