Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
I am trying to make my own Set() method in JavaScript. But getting unexpected output

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] 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!