DoeDoeDoe DoeDoeDoe - 1 month ago 6
Javascript Question

Compare a word against words in an array

Write a function

offOne(word, book)
which takes
a string called
word
and an array of strings called
book
.
It returns an array of all the
word
s in
book
of the same
length that are one letter different.

Examples:

offOne("cat", ["cat", "fat", "flat", "tar"]) => ["fat", "tar"]
offOne("will", ["wilt", "willow", "wail"]) => ["wilt", "wail"]


My function is currently:

function offOne(word, book) {
var array = [];
var count = 0;

for (var i = 0; i < book.length; i++) {
if (book.length === word.length) {
if (word.indexOf(book[i]) !== -1) {
count += 1;

if (count === (book[i].length - 1)) {
array.push(book[i]);
}
}
}
}
return array;
}


Does anyone know how to solve this? I got stuck for a while here.

Answer

Steps:

  1. Make a function that compares two strings with the same length.
  2. Make a function that compares the word with the words within the array with the help of the compareStrings().

In total:

var word = "cat";
var book = ["car", "eagle", "fat", "cam", "shoe"];

// First step

function compareStrings(str1, str2) { // The two strings (words) have the same length
  var len = str1.length;
  var count = 0;
  var i = 0;
  while (i < len) {
    if (str1[i] !== str2[i]) {
      count += 1;
    }
    i += 1;
  }
  return count === 1 ? true : false; // Return true if there is one char different
}

// Second step

function offOne(word, book) {
  var len = word.length;
  var res = [];
  book.forEach(w => {
    if (w.length === len) { // If they have the same length
      if (w !== word) { // If they are not the same
        if (compareStrings(w, word) === true) { // If one char is different
          res.push(w);
        }
      }
    }
  });
  return res;
}

var res = offOne(word, book);
console.log(res);

P.S Your second example should only output ['wilt'].