JavaScript Katas: Remove duplicates
Tags: javascript, beginners, webdev, codenewbie
Published: 2020-07-21 09:35:35

---
title: "JavaScript Katas: Remove duplicates"
description: "We learn how to use a for loop, a lot of functional stuff and Set"
published: true
tags: ["JavaScript", "Beginners", "Webdev", "Codenewbie"]
series: JavaScript Katas with miku86
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/0jfyzv0grswtx1mlo17m.jpg
---

## Intro 🌐

I take interesting katas of all levels and explain how to solve them.

Problem solving is an important skill, for your career and your life in general.

You'd better learn to solve problems!

---

## Source

I take the ideas for the katas from different sources and re-write them.

Today's source: [Codewars](https://www.codewars.com/kata/57a5b0dfcf1fa526bb000118)

---

## Understanding the Exercise ❗

First, we need to understand the exercise!

This is a crucial part of (software) engineering.

Go over the exercise explanation again until you understand it 100%.

Do NOT try to save time here.

My method to do this:

1. Input: What do I put in?
2. Output: What do I want to get out?

---

### Today's exercise

Write a function `removeDuplicates`, that accepts one parameter: `inputArray`.

Given a numbers array, e.g. `[1, 1, 2]`, return a numbers array without duplicates, e.g. `[1, 2]`. The order of the sequence has to stay the same.

---

Input: a numbers array.

Output: a numbers array.

---

## Thinking about the Solution 💭

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps.

1. Loop over every number
1. Check if current number has been seen before
1. If no (= not seen), save it into the results
1. Return results

---

Example:

- Input: `[1, 1, 2]`
- Iteration 1: `1` been seen? => `No` => save it => `[1]`
- Iteration 2: `1` been seen? => `Yes` => do nothing => `[1]`
- Iteration 3: `2` been seen? => `No` => save it => `[1, 2]`
- Output: `[1, 2]` ✅

---

## Implementation (for loop) ⛑

```js
function removeDuplicates(inputNumbers) {
  // variable to save result
  const withoutDuplicates = [];

  // loop over every number
  for (const number of inputNumbers) {
    // check if current number has been seen before
    // if no (= not seen), save it into the results
    if (!withoutDuplicates.includes(number)) {
      withoutDuplicates.push(number);
    }
  }

  // return result
  return withoutDuplicates;
}
```

## Result

```js
console.log(removeDuplicates([1, 1, 2]));
// [ 1, 2 ] ✅

console.log(removeDuplicates([3, 3, 2, 2, 1]));
// [ 3, 2, 1 ] ✅
```

---

## Implementation (functional) ⛑

```js
function removeDuplicates(inputNumbers) {
  return inputNumbers.reduce(
    (accumulated, current) => {
      // check if current number has been seen before
      return accumulated.includes(current)
        ? accumulated // if yes (= already seen), return the old values without changes
        : accumulated.concat(current); // if no (= not seen), return the old values plus the current one
    },
    [] // we start with an empty array (like "withoutDuplicates" in the alternative solution)
  );
}
```

I'm using [`concat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) to connect the old values with the current one. You can also use the spread operator like we did [here](https://dev.to/miku86/javascript-katas-count-sheep-2e7e).

## Result

```js
console.log(removeDuplicates([1, 1, 2]));
// [ 1, 2 ] ✅

console.log(removeDuplicates([3, 3, 2, 2, 1]));
// [ 3, 2, 1 ] ✅
```

---

## Implementation (Set) ⛑

```js
function removeDuplicates(inputNumbers) {
  // we go from array (inputNumbers) to set (new Set()) to array (...)
  return [...new Set(inputNumbers)];
}
```

In JavaScript, in the `Set` data structure a value may only occur once and the order is preserved, so this solves our problem too. If you don't use JavaScript, pay attention to the fact, that not every programming language keeps the original order in a `Set`. (Thanks to [@pentacular](https://dev.to/pentacular/comment/12ajl))

We use a temporary change in the data structure (a `Set`) to remove our duplicates. Then we convert the `Set` back to an array.

## Result

```js
console.log(removeDuplicates([1, 1, 2]));
// [ 1, 2 ] ✅

console.log(removeDuplicates([3, 3, 2, 2, 1]));
// [ 3, 2, 1 ] ✅
```

---

## Playground ⚽

You can play around with the code [here](https://repl.it/@miku86/js-katas-remove-duplicates)

---

## Next Part ➡️

Great work, mate!

We learned how to use a `for of` loop, a lot of functional stuff and `Set`.

I hope that you can use your new learnings to solve problems more easily!

Next time, we'll solve another interesting kata. Stay tuned!

---

If I should solve a specific kata, shoot me a message [here](https://forms.gle/RmQLq7CLDiD2Ptmw5).

If you want to read my latest stuff, [get in touch with me!](https://miku86.com/newsletter)

---

## Further Reading 📖

- [for of loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
- [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)
- [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
- [[...]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
- [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)

---

## Questions ❔

- How often do you do katas?
- Which implementation do you like more? Why?
- Any alternative solution?
- Have you ever used a `Set`?