What I'm trying to do:
I'm trying to calculate the distance between two words in a string (in our example, var someString = "one two three four five six seven". As you can see in my code below, I convert the string to an array with the split() method, then call the function minDist()that calculates the distance between the words.
What's the problem:
As you can see in the code and my relevant comments, everything works as intended if I call the function using the string (or rather, the array, "one", "two", "three", "four", "five", "six", "seven") directly. The result is, as expected, 3 - which is the distance between "one" and "four" in this specific example.
However, as you can see, if I try to call the function using the array's variable, the result is null.
Why is that and how can I resolve this problem?
var someString = "one two three four five six seven"
var distanceCheck = someString.split(" ");
console.log("distanceCheck",distanceCheck,"Quick test. As expected, the result is: one,two,three,four,five,six,seven")
for (var i = 0; i < distanceCheck.length; i++) {
distanceCheck[i] = '"' + distanceCheck[i] + '"';
}
var list2b = distanceCheck.join(", ");
console.log("list2b",list2b,'As expected, the result is: "one", "two", "three", "four", "five", "six", "seven"')
var check0 = minDist(["one", "two", "three", "four", "five", "six", "seven"], "one", "four");
console.log("check0",check0,"Result is: 3")
var check1 = minDist([list2b], "one", "four");
console.log("check1",check1,"Result is: null. WHY?")
function minDist(words, wordA, wordB) {
var wordAIndex = null;
var wordBIndex = null;
var minDinstance = null;
for (var i = 0, length = words.length; i < length; i++) {
if (words[i] === wordA) {
wordAIndex = i;
}
if (words[i] === wordB) {
wordBIndex = i;
}
if (wordAIndex !== null && wordBIndex !== null) {
var distance = Math.abs(wordAIndex - wordBIndex);
if (minDinstance === null || minDinstance > distance) {
minDinstance = distance;
}
}
}
return minDinstance;
}