I have an array, arr = [0, 0, 0, 0, 1, 1]. The argument being passed into a function contains this array and also a numeric value which happens to be 1 in this example. My function is called pairwise and looks like this:
function pairwise(arr, arg) {
...some code ...
}
pairwise([0, 0, 0, 0, 1, 1], 1);
If an element pair in the array adds up to the second argument passed to the function then I need to add the indices of each unique pair and return the sum of the indices. For this example, the sum would be 10 because index 0 and 4 adds to 1 and also index 1 and 5 add to one, so the sum of indices 0 + 4 + 1 + 5 = 10. I cannot count the same index twice.
Inside my function, I subtract arg from arr[i] inside a for loop that loops over the length of the array. Then I take the result from that subtraction and use arr.indexOf(result) to find the index pair, if it exists. Everything is working fine until I encounter this problem. indexOf only looks for the first occurrence and when I run my code it doesn't count the second 1 in arr so I am unable to get the second pair. My sum is 4 when it should be 10. Here is the rest of my code:
function pairwise(arr, arg) {
var array = [];
if (arr.length != 0) {
for (var i=0; i<arr.length; i++) {
if (arr.indexOf(arg - arr[i]) != -1) {
if (array.indexOf(i) === -1 && array.indexOf(arr.indexOf(arg-arr[i])) === -1) {
if (i !== arr.indexOf(arg - arr[i])) {
array.push(i,arr.indexOf(arg - arr[i]));
}
}
}
}
} else {
return 0;
}
console.log (array);
return array.reduce(function(a,b) {return a+b;});
}
pairwise([0, 0, 0, 0, 1, 1], 1);
I also push the result into an array so I am limited to Array.prototype methods. I tried looking for other methods to use but I can't find any that I can implement with what I am doing. Maybe you know of one easier way to do this? My question is, is there a way to look past the first index match of indexOf. Should I use another method to approach my solution?