create a function that compares two strings and finds what is different in javascript

Here's a function that takes two strings as arguments and returns an array of differences between them:

index.tsx
function findDifferences(str1, str2) {
  let output = [];
  for (let i = 0; i < str1.length; i++) {
    if (str1[i] !== str2[i]) {
      output.push([str1[i], str2[i]]);
    }
  }
  return output;
}
199 chars
10 lines

This function uses a loop to iterate through each character in the strings. It compares each character at the same position in both strings and adds a tuple of the differing characters to an output array if they are not the same.

Testing this function with two strings "hello" and "hella" would return an array with one item: [["o", "a"]]. This indicates that the only difference between the two strings is that the "o" in "hello" is replaced by an "a" in "hella".

gistlibby LogSnag