how to check array for duplicates javascript code example

Example 1: javascript check if array has duplicates

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

Example 2: how to get duplicate values from array in javascript

let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]

// b is now [1, 2, 4]

Example 3: javascript duplicate an array

let arr =["a","b","c"];
// ES6 way
const duplicate = [...arr];

// older method
const duplicate = Array.from(arr);

Example 4: check for duplicates in array javascript

[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true

[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false

Tags:

Java Example