以下函数查找在数组中出现多次的单词对,然后将它们组合成单个数组元素。它适用于示例数组,但在我尝试将其实现到我的项目中时失败(它通过抓取网页动态创建数组)。
功能:
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来演示。为什么第二个数组不起作用?
答案 0 :(得分:1)
构建字典时似乎有一个错误,这导致数组的最后一个字不被添加到字典中。第一个例子有效,因为最后一个单词(“smith”)先前已包含在数组中。
第三行应为for (var a = 0; a < arr.length; a++) {
,即:
function combineCommon(arr) {
var dictionary = {};
for (var a = 0; a < arr.length; 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));
答案 1 :(得分:1)
您尚未在第18行进行未定义检查:
jsfiddle更新如下:
return new Promise<void>((resolve) => {
setTimeout(() => {console.log("1"); resolve()}, 1000);
});