Blog

Code to Get Unique Elements of an Array using ES6 Syntax
Posted on February 6, 2019 in Algorithms, JavaScript by Matt Jennings

const arr1 = [2, 2, 4, 2, 6, 4, 7, 8]

const counts = {}

let i

for (i = 0; i < arr1.length; i++) { 
    let value = arr1[i]; 
    if (typeof counts[value] === "undefined") { 
        counts[value] = 1 
    } 
    else { 
        counts[value]++ 
    } 
}

console.log(counts)

const arr2 = arr1.filter(key => { 
    let value = counts[key] 
    return value === 1 
})
.sort((a, b) => {
    return a - b
})

console.log(arr2)

Leave a Reply

To Top ↑