DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Edited on

5 2

#8 - Simple remove duplicates CodeWars Kata (7 kyu)

Instructions:

Remove the duplicates from a list of integers, keeping the last ( rightmost ) occurrence of each element.

Example:

For input: [3, 4, 4, 3, 6, 3]
remove the 3 at index 0
remove the 4 at index 1
remove the 3 at index 3
Expected output: [4, 6, 3]

My solution:


function solve(arr) {
  let newArr = arr.slice().filter((n, i) => arr.indexOf(n) !== i)
  for(let i = 0; i< newArr.length; i++){
    arr.splice(arr.indexOf(newArr[i]), 1)
  }
  return arr
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I made a new array so I could get the repeated numbers, for this I sliced the arr var, so it makes a new array, then I filtered that new array using the condition that will filter if the index of the current number in the original array isn't the same as the one that is currently getting mapped, because remember that .indexOf() only takes the index of the first number in the array

After that I used a for loop that will execute for every element that is repeated, after that I spliced the original array, locating the elimination direction in the index of the repeated element in the original array.

After that I just returned arr

What do you think about this solution? 👇🤔

Follow me on twitter
My Github
Solve this Kata

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or a friendly comment!

Okay.