Why Can't This Function Process This Particular Array?
The following function finds word pairs that appear more than once in an array, then combines them into a single array element. It works on the example array, but fails when I try
Solution 1:
There seems to be an off by one error when building the dictionary, which is causing the last word of the array not to be added to the dictionary. The first example works because the last word ("smith") is already included previously in the array.
The third line should be for (var a = 0; a < arr.length; a++) {
, ie:
functioncombineCommon(arr) {
var dictionary = {};
for (var a = 0; a < arr.length; a++) {
var A = arr[a];
if (dictionary[A] == void0) {
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));
Post a Comment for "Why Can't This Function Process This Particular Array?"