score:3

Accepted answer

D3 has a quite unknown method, named d3.zip, which we can use to merge the arrays and look for any inner array in which all the elements are equal:

var line1 = [0, 1, 2, 3, 4];
var line2 = [4, 3, 2, 1, 0];
var zip = d3.zip(line1, line2).reduce(function(a, c, i) {
  if (c[0] === c[1]) a.push(i);
  return a;
}, []);

console.log(zip)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

The nice thing about d3.zip is that it can be used with several arrays, and also keeps the length of the shorter array. So, in a more complex case (equal values in the indices 6 and 9):

var line1 = [0, 1, 2, 3, 9, 9, 1, 4, 7, 6, 5, 4];
var line2 = [4, 3, 2, 1, 0, 8, 1, 2, 3, 6, 1];
var line3 = [9, 9, 9, 9, 4, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1];
var zip = d3.zip(line1, line2, line3).reduce(function(a, c, i) {
  const every = c.every(function(e) {
    return e === c[0]
  })
  if (every) a.push(i);
  return a;
}, []);

console.log(zip)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

score:-1

const [longer, shorter] = line1.length > line2.length ? [line1, line2] : [line2, line1];

const crossIndex = shorter.reduce((crossIndex, value, index) => {
  if (crossIndex !== null) {
    // already found it! just return
    return crossIndex;
  }

  // find it! return
  if (value === longer[index]) return index;

  // no found, continue searching
  return crossIndex;
}, null)

If you don't mind the search running a few extra useless iterations, the first step where we find out which line is longer or shorter, is actually not necessary. You call .reduce() on either line1 or line 2, then compare again the other, you'll still get the same result.


Related Query

More Query from same tag