I'm kind of wanted to create my own set() method as mySet() for unique element from an array. But getting wrong output. help me out.
let arr = [1,2,3,4,5,2,8,1,3,1]
function mySet(arr){
let mapObj = {}
let newArr = []
for (let i = 0; i <arr.length; i++) {
if(mapObj[arr[i]]){
//skip
}else{
mapObj[arr[i]]=i
newArr.push(arr[i])
}
}
return newArr;
}
console.log(mySet(arr)) //i wanted [1,2,3,4,5,8] getting [1,2,3,4,5,8,1]
You need a truthy value for the object in this case, you can use true.
The check returns with zero (the first index) the same result as if you have not assigned any value to the property.
function mySet(arr) {
let mapObj = {}
let newArr = []
for (let i = 0; i < arr.length; i++) {
if (!mapObj[arr[i]]) {
mapObj[arr[i]] = true;
newArr.push(arr[i])
}
}
return newArr;
}
let arr = [1, 2, 3, 4, 5, 2, 8, 1, 3, 1]
console.log(mySet(arr));
mapObj[arr[i]]=i assigns the current index.
if(mapObj[arr[i]]){ treats the value as a boolean.
The first index of the value 1 occurs at 0.
So you say mapObj[1] = 0 which is false.
You need to assign true instead of i.