Search code examples
javascriptarrayscomparison

How can I compare 2 different arrays index wise?


From Index wise I mean:
If there are two arrays A and B then, the item at index 0 in array A compares to item at index 0 in array B.

Here is the example to work on:

let start = ['m', 'y', 'a', 'g', 'e', 'i', 's'];

let end = ['y', 'm', 'a', 'g', 'e', 'i', 's'];

You must not do it this way((a[1] === b[1])) because you don't know how long the array can be


Solution

  • You can use a standard for-loop to iterate over the indices of the start (or end) array. While looping, you can check the values for each array at that index and compare them.

    You only return true if you do not break out of the function early.

    function areEqual(start, end) {
      if (start === end) {
        return true; // Same memory address
      }
      if (start.length !== end.length) {
        console.error('Length of arrays do not match!');
        return false;
      }
      for (let index = 0; index < start.length; index++) {
        if (start[index] !== end[index]) {
          console.error(`Values at index ${index} do not match`);
          return false;
        }
      }
      return true; // Equal!
    }
    
    const start = ['m', 'y', 'a', 'g', 'e', 'i', 's'];
    const end = ['y', 'm', 'a', 'g', 'e', 'i', 's'];
    
    console.log(areEqual(start, end));

    Here is an ES6 version, but it does not have error-checking. It simply returns true or false.

    const
      start    = ['m', 'y', 'a', 'g', 'e', 'i', 's'],
      end      = ['y', 'm', 'a', 'g', 'e', 'i', 's'],
      other    = ['m', 'y', 'a', 'g', 'e', 'i', 's'],
      areEqual = (a, b) =>
                   (a === b) || (a.length === b.length && !a.some((x, i) => x !== b[i]));
    
    console.log(areEqual(start, end));   // Diff  -- false
    console.log(areEqual(start, start)); // Same  -- true
    console.log(areEqual(start, other)); // Equal -- true