Blog

Remove Duplicates from Array in JavaScript
Posted on July 24, 2019 in Algorithms, JavaScript by Matt Jennings

function removeDuplicates(arr) {
  var arrNoDupes = [];
  
  // Iterate through array passed in by parameter
  // and if element is NOT in array
  // then push element into arrNoDupes
  for(var i = 0; i < arr.length; i++) {
    if(!arrNoDupes.indexOf(arr[i])) {
      arrNoDupes.push(arr[i]);
    }
  }
  
  // Sort arrNoDupes into an ascending array
  // and assign result to arrNoDupesSorted
  var arrNoDupesSorted = arrNoDupes.sort(function(num1, num2) {
    return num1 - num2;
  });
  
  return arrNoDupesSorted;
}

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

console.log(removeDuplicates([4,5,4,4,7,5]));
// [4, 5, 7]

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

Leave a Reply