Remove Duplicate Values
by trentHarlem
JavaScript
// what is the EXPECTED OUTPUT?
let a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1]
// Expected output : [1,2,3,4,5,6]
let b = []
let len = a.length
//Method one:
/* for (let i = 0; i < len; i++) {
if (b.indexOf(a[i]) === -1) {
b.push(a[i])
}
}
console.log(b) */
//Method two:
/* a.sort() // to arrange duplicate values
let temp // to hold the previous value
for (let i = 0; i < len; i++) {
if (a[i] !== temp) {
b.push(a[i])
temp = a[i] // reset the 'previous' value every iteration
}
}
console.log(b) */
//Method three:
// hash
a = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1]
//a = [1, 2, 3, 4, 5]
/* obj = {}
//obj require UNIQUE keys
for (let i of a) {
obj[i] = true
}
// javascript filters out duplicates
//as duplicate object keys are not allowed
console.log(obj)
//b = Array.from(Object.keys(obj))
b = Object.keys(obj)
let b2 = Object.values(obj)
let b3 = Object.entries(obj)
console.log(b)
console.log(b2)
console.log(b3)
*/
//Method four
//let bSet = new Set(a)
let bSet = [...new Set(a)]
console.log(bSet)