JavaScript function that finds duplicates in an Array prints results twice. How to fix?

Viewed 111

The JavaScript code I am using right now scans through an array and finds duplicates. But if there are more than two entries in the array that are the same, it prints that entry twice.

Please see Code Snippet where the Array arr has the string "one" three times so that output is printed twice.

How do I edit my JavaScript function so the output does not print the duplicates twice?

var arr = ["one", "two", "one", "three", "one", "four", "two", "five", "six"];
var cache = {};
var results = [];
for (var i = 0, len = arr.length; i < len; i++) {
  if(cache[arr[i]] === true){
      results.push(arr[i]);
   }else{
       cache[arr[i]] = true;
   }

}

console.log(results)

2 Answers

You can store the number of occurrences instead of a boolean:

var arr = ["one", "two", "one", "three", "one", "four", "two", "five", "six"];
var cache = {};
var results = [];
for (var i = 0, len = arr.length; i < len; i++) {
  if(cache[arr[i]] === 1){
      results.push(arr[i]);
      cache[arr[i]] += 1;
   }else{
       cache[arr[i]] = 1;
   }

}

console.log(results)

Use another cache

var arr = ["one", "two", "one", "three", "one", "four", "two", "five", "six"];
var cache = {};
var cache2 = {};
var results = [];
for (var i = 0, len = arr.length; i < len; i++) {
  if (cache[arr[i]] === true) {
    cache2[arr[i]] = true
  } else {
    cache[arr[i]] = true;
  }

}

console.log(Object.keys(cache2))

Related