Die folgende Funktion findet Wortpaare, die mehr als einmal in einem Array vorkommen, und kombiniert sie dann zu einem einzelnen Array-Element. Es funktioniert auf dem Beispiel-Array, schlägt aber fehl, wenn ich versuche, dies in mein Projekt zu implementieren (das dynamisch ein Array aus Scraping-Webseiten erstellt).Warum kann diese Funktion dieses bestimmte Array nicht verarbeiten?
Funktion:
function combineCommon(arr) {
var dictionary = {};
for (var a = 0; a < arr.length - 1; a++) {
var A = arr[a];
if (dictionary[A] == void 0) {
dictionary[A] = [];
}
dictionary[A].push(arr[a + 1]);
}
var res = [];
for (var index = 0; index < arr.length; index++) {
var element = arr[index];
var pass = false;
if (dictionary[element].length > 1) {
if (dictionary[element]
.some(function(a) {
return a != dictionary[element][0];
}) == false) {
pass = true;
}
}
if (pass) {
res.push(arr[index] + " " + dictionary[element][0]);
index++;
} else {
res.push(arr[index]);
}
}
return res;
}
console.log(combineCommon(arr));
Array, das funktioniert:
var arr = ["john", "smith", "says", "that", "a", "lock", "smith", "can", "open", "the", "lock", "unlike", "john", "smith"];
Array das nicht funktioniert:
var arr = ['Social', 'care', 'fund', 'fails', 'to', 'reduce', 'pressure', 'on', 'hospital', 'beds', 'Court', 'questions', 'whether', 'US', 'travel', 'ban', 'is', 'anti', 'Muslim', 'Police', 'pay', 'out', 'at', 'least', '£195m', 'to', 'informants', 'in', 'five', 'years', 'Brexit', 'rebellion', 'avoided', 'after', 'meaningful', 'vote', 'offer', 'FA', 'reforms', 'Chairman', 'Greg', 'Clarke', 'to', 'quit', 'if', 'government', 'does', 'not', 'back', 'plans', 'Louisiana', 'tornadoes', 'The', 'whole', 'house', 'fell', 'apart', 'Uncertainty', 'over', '30', 'hours', 'free', 'childcare', 'say', 'councils', 'Uncertainty', 'over', '30', 'hours', 'free', 'childcare', 'say', 'councils', 'Hans', 'Rosling', 'Data', 'visionary', 'and', 'educator', 'dies', 'aged', '68', 'Dakota', 'Access', 'Pipeline', 'to', 'win', 'US', 'Army', 'permit', 'for', 'completion']
Hier ist ein jsfiddle zu demonstrieren. Warum funktioniert das zweite Array nicht?
Sie müssen entscheiden, wie man mit dem letzten Wort umgeht. Wenn die Eingabe '[' john ',' smith ',' john ',' smith ',' john '] ist, sollte die Funktion' ['john smith', 'john smith', 'john'] 'oder' 'zurückgeben Sollte es keinem der Wörter beitreten? – Stuart