Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
Reduce method of array not reaching last element

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!