Pairwise - current item vs. array[index] in reduce method

Pairwise - current item vs. array[index] in reduce method
0

#1

Hey, I have a question about line 4 (the if condition) in this working code. Why does this work with array[index] but not with the current item curr? It seems like they’d be the same thing. Thanks!

function pairwise(arr, arg) {
return arr.reduce(function(acc, curr, index, array) {
    for (var i = index + 1; i < array.length; i++) {
      if (array[index] + array[i] === arg) {
        acc += index + i;
        array.splice(index, 1, NaN);
        array.splice(i, 1, NaN);
      }
    }
    return acc;
  }, 0);

}

pairwise([1, 1, 1], 2); //should return 1.

#2

After you do this:

array.splice(index, 1, NaN);

array[index] will be NaN and

if (array[index] + array[i] === arg)

will never be true.

But if you use curr, it can match something else. To avoid that add break after your splices.


#3

Thanks for the response. Adding the break does make all the difference in console output. I’m thinking curr acts like a temporary variable while the for loops complete unless stopped, but array[index] accesses the value directly each time it’s involved in a calculation. That’ll do it!