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

84
Views
Iterating over Map object

I'm new to javascript and I'm trying to understand how to use the Map feature. I have an array of numbers, and if the value is 0, I want the key of the object to be false, and for any other value; true.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Welcome to stackoverflow! What you need to know is that a key is unique in a map object. You have only two keys which are true and false. So, if you try to insert into the map a key that already exists, then it will be updated with the new key/value pair you are setting. This is why you only see two key/value pairs as output. Also as a little side-note when you declare values of array1 since you are working with a single element in each iteration of the loop it would be better to have value of array1 to make the code a little more cleaner.

about 4 years ago · Juan Pablo Isaza Report

0

Since map key is unique, so you got only two keys. If you want to get maps for each values, you can make a pair of key and value and then insert it into an array.

const array1 = [1,0,1,0,1,-1];

let result = [];
for (values of array1 ) {
    if (values !== 0) {
        const mapExample = new Map(); 
        mapExample.set(true, values)
        result.push(mapExample)
    } else {
        const mapExample = new Map(); 
        mapExample.set(false, values)
        result.push(mapExample)
    }
}

console.log(result)

the result would be like this

[
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { false => 0 },
  Map(1) { true => 1 },
  Map(1) { true => -1 }
]
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!