次の関数は、配列に複数回現れる単語のペアを見つけ、それらを1つの配列要素に結合します。これはサンプル配列で動作しますが、これをプロジェクトに実装しようとすると失敗します(動的にWebページをスクラップして配列を作成します)。なぜこの機能はこの特定のアレイを処理できませんか?
機能:作品
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));
は、アレイ:動作しません
var arr = ["john", "smith", "says", "that", "a", "lock", "smith", "can", "open", "the", "lock", "unlike", "john", "smith"];
は、アレイ:
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']
ここにはjsfiddleがあります。 2番目の配列が機能しないのはなぜですか?
をあなたがする必要があります最終的な言葉に対処する方法を決めます。入力が '['john'、 'smith'、 'john'、 'smith'、 'john']'の場合、関数は '['john smith'、 'john smith'、 'john']'を返します。どんな言葉にも参加してはいけませんか? – Stuart