1let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
2let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)
3
4console.log(findDuplicates(strArray)) // All duplicates
5console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates
1var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];
2
3console.log([...new Set(
4 array.filter((value, index, self) => self.indexOf(value) !== index))]
5);
1let arr =["a","b","c"];
2// ES6 way
3const duplicate = [...arr];
4
5// older method
6const duplicate = Array.from(arr);
1const arr = ["q", "w", "w", "e", "i", "u", "r"]
2arr.reduce((acc, cur) => {
3 if(acc[cur]) {
4 acc.duplicates.push(cur)
5 } else {
6 acc[cur] = true //anything could go here
7 }
8}, { duplicates: [] })
1const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']
2
3const count = names =>
4 names.reduce((a, b) => ({ ...a,
5 [b]: (a[b] || 0) + 1
6 }), {}) // don't forget to initialize the accumulator
7
8const duplicates = dict =>
9 Object.keys(dict).filter((a) => dict[a] > 1)
10
11console.log(count(names)) // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 }
12console.log(duplicates(count(names))) // [ 'Nancy' ]
1function checkIfDuplicateExists(w){
2 return new Set(w).size !== w.length
3}
4
5console.log(
6 checkIfDuplicateExists(["a", "b", "c", "a"])
7// true
8);
9
10console.log(
11 checkIfDuplicateExists(["a", "b", "c"]))
12//false