So I'm really new to JavaScript, and I'm having a bit trouble with reduce method in JavaScript which doesn't reach the last element of the array. My function removes duplicates from array by first sorting the array, and then using the reduce method to delete element if first and second element are same.
I'm thinking maybe it has something to do with the splice method I use in conjunction with it. But I'm not entirely sure what is going on, can someone help explain what's happening here?
function removeduplicate3(arr) {
arr.sort((first, second) => (first > second));
console.log(arr);
arr.reduce((first, second) => {
console.log(`${first} ${second}`); // check pair of elements it reduces
if (first === second) {
arr.splice(arr.indexOf(second), 1)
return first;
} else
return second;
}, undefined);
}
let arr = ["Hello", "World", "Bye", "World", "I", "Am", "I", "World"];
console.log(removeduplicate3(arr));
my finally (incorrectly) filtered array has: [ "Am", "Bye", "Hello", "I", "World", "World" ]
I printed the pairs of elements of array with ${first} ${second}
, and it's missing the last pair: World World