I created one function with JavaScript which compare two string and return the number of the same characters with the following logic:
Char 1 = “aaabc” | Char 2 = “aakbc” ===> My function return 2
Char 2 = “88835” | Char 2 = “888vbr” ===> My function return 3
Char 1 = “A1234” | Char 2 = “B1234” ===> My function return 0
The logic is that when the function find that the FIRST character of CHAR1 is DIFFERENT is NOT EQUAL than the FIRST character of CHAR2 the function stop the iteration and return 0, if not: the function continue until we find that the CHAR1(i) !== CHAR2(i).
I am using this function to compare between two array of string, T[i] and V[j]. For each value of T[i] I am browsing all V[j] and returning the row which is more similar that T[i] and if the function find same result, I will return the smallest value V[j]. This is the code that I used:
function MyFunction(a, b) {
var n = a.length,
m = b.length;
var v;
var i = 1;
var j = 1;
if (a === b) {
v = a.length;
} else
if (a.charCodeAt(0) !== b.charCodeAt(0)) {
v = 0;
} else {
v = 1;
for (i = 1; i < n; i++) {
if (a.charCodeAt(i) == b.charCodeAt(i)) {
v++;
} else {
return v;
}
}
}
return v;
}
var t = ["350", "840", "35"],
v = ["3506", "35077", "84"],
i, j, f, l,
max,
result = [],
row = [];
for (i = 0; i < t.length; i++) {
max = MyFunction(v[0], t[i]);
l = v[0].length;
f = [
[t[0]],
[v[0]]
];
for (j = 1; j < v.length; j++) {
if (MyFunction(v[j], t[i]) > max) {
max = MyFunction(v[j], t[i]);
f = [
[t[i]],
[v[j]]
];
l = v[j].length;
} else {
if (MyFunction(v[j], t[i]) == max && l > v[j].length) {
max = MyFunction(v[j], t[i]);
f = [
[t[i]],
[v[j]]
];
l = v[j].length;
} else {
continue;
}
}
}
result.push(f);
console.log(f);
}
My code have an issue, the result which I have is:
[350][3506] (Correct value)
[840][84] (Correct value)
[350][3506] (Wrong value)
I don’t find a solution for this issue, my code don’t compare the value [35], the code is comparing the first value [350] (this is the issue).
t, and "35" is missing, he gets double results for "350" insteadfunction MyFunction(a,b) {for( var i=0, l=Math.min(a.length,b.length); i<l; i++) {if(a[i] !== b[i]) {return i;}} return l;}Job done.