Creating A New Array Without The Duplicates

Brian Smith
1 min readJul 8, 2021

--

It is always fun discovering and learning a new method that you never thought existed. After spending hours trying to iterate through an array and then remove duplicates on a project, I learned how to create a new array without the duplicates. Since I found it very helpful, I thought a short post about this method would be useful to others who may be stuck in an endless loop trying to figure it out.

After feeling stumped and frustrated, I finally asked a few friends for guidance — something I should have done sooner. Thankfully they were able to help and suggested that I use the Set. The Set method is a much simpler way to create a new array by cloning the original (or old) array while removing the duplicate elements. Set object lets you store unique values of any type, whether primitive values or object references, and iterates through elements so that they only occur once.

Below is an example of how to use the Set method. I took a variable (const oldArray) and set it equal to an array ([1, 4, “hi”, 4, 3, “hi”]). Then I took that variable and used the spread operator with the Set method to make a new array without the duplicates.

const oldArray = [1, 4, “hi”, 4, 3, “hi”]

const newArray = […new Set(oldArray)]

Console.log(newArray) =====> [1, 4, “hi”, 3]

--

--