repl.it
@ashenm/

Pairwise

JavaScript

Specimen code solution for freeCodeCamp advanced algorithm scripting challenge.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Pairwise
 * https://www.freecodecamp.org/challenges/pairwise
 * Returns the sum of element pairs indices whose sum equal the second argument
 *
 * Ashen Gunaratne
 * [email protected]
 *
 */

function pairwise(arr, arg) {
  return arr.reduce((accumulator, value, index, array) => {
    const pair = array.indexOf(arg - value , index + 1);
    if (pair > -1) {
      delete array[pair];
      delete array[index];
      accumulator += index + pair;
    }
    return accumulator;
  }, 0);
}

// test here
pairwise([1,4,2,3,0,5], 7);
Native Browser JavaScript