Seeking a solution to eliminate any duplicate numbers from two arrays:
function removeDuplicates(args) {
var uniqueNumbers = [].concat.apply([],arguments).reduce(
function(result, current) {
console.log("result: " + result);
console.log("current: " + current);
console.log("result.indexOf(current): " + result.indexOf(current));
return result.indexOf(current) === -1
? result.concat(current)
: result.splice(result.indexOf(current), 1);
}, []
);
console.log("uniqueNumbers: " + uniqueNumbers);
return uniqueNumbers;
}
console.clear();
removeDuplicates([1, 2, 3], [5, 2, 1, 4]);
However, the output in the console shows:
Console was cleared
result:
current: 1
result.indexOf(current): -1
result: 1
current: 2
result.indexOf(current): -1
result: 1,2
current: 3
result.indexOf(current): -1
result: 1,2,3
current: 5
result.indexOf(current): -1
result: 1,2,3,5
current: 2
result.indexOf(current): 1
result: 2
current: 1
result.indexOf(current): -1
result: 2,1
current: 4
result.indexOf(current): -1
uniqueNumbers: 2,1,4
The concern arises as to why the slice statement is not functioning as intended and instead resets the result variable with the current value?
I initially expected that the line `result.splice(result.indexOf(current), 1)` upon finding a match would result in:
1,3,5
Instead of
2