Home  »  CodeGuidesLibrariesProgrammingSnippetsTechnologyTools   »   Remove all Duplicates From an Array in JavaScript

Remove all Duplicates From an Array in JavaScript

Posted: January 2, 2023 | by Michael Bright

Here is the code that you can use to remove all duplicates from an array in JavaScript.

const numbers = [1 , 21, 21, 34 ,12 ,34 ,12];
const removeRepeatNumbers = array => [... new Set(array)]
removeRepeatNumbers(numbers) // [ 1, 21, 34, 12 ]

const removeDuplicates = arr => [...new Set(arr)];

// Remove Duplicates ES6
const uniqueArray = oldArray.filter((item, index, self) => self.indexOf(item) === index);

let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue)
  }
  return accumulator
}, [])
console.log(myOrderedArray); // [ 'a', 'b', 'c', 'd', 'e' ]

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.