javascript array duplicate code example

Example 1: js delete duplicates from array

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'

Example 2: javascript remove duplicate in arrays

// 1. filter()
function removeDuplicates(array) {
  return array.filter((a, b) => array.indexOf(a) === b)
};
// 2. forEach()
function removeDuplicates(array) {
  let x = {};
  array.forEach(function(i) {
    if(!x[i]) {
      x[i] = true
    }
  })
  return Object.keys(x)
};
// 3. Set
function removeDuplicates(array) {
  array.splice(0, array.length, ...(new Set(array)))
};
// 4. map()
function removeDuplicates(array) {
  let a = []
  array.map(x => 
    if(!a.includes(x) {
      a.push(x)
    })
  return a
};
/THIS SITE/ "https://dev.to/mshin1995/back-to-basics-removing-duplicates-from-an-array-55he#comments"

Example 3: count duplicates array js

uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);

Example 4: javascript remove duplicates from array

function toUniqueArray(a){
    var newArr = [];
    for (var i = 0; i < a.length; i++) {
        if (newArr.indexOf(a[i]) === -1) {
            newArr.push(a[i]);
        }
    }
  return newArr;
}
var colors = ["red","red","green","green","green"];
var colorsUnique=toUniqueArray(colors); // ["red","green"]

Example 5: js delete duplicates from array

const names = ['John', 'Paul', 'George', 'Ringo', 'John'];

function removeDups(names) {
  let unique = {};
  names.forEach(function(i) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  return Object.keys(unique);
}

removeDups(names); // // 'John', 'Paul', 'George', 'Ringo'

Example 6: duplicate numbers in an array javascript

[1, 1, 2, 2, 3].filter((element, index, array) => array.indexOf(element) !== index) // [1, 2]