fdsvsfvfs
fdsvsfvfs

Reputation: 1

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.

Upvotes: 0

Views: 337

Answers (2)

alonealgorithm
alonealgorithm

Reputation: 149

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.

Upvotes: 2

ishlahmuzakki
ishlahmuzakki

Reputation: 63

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 }
]

Upvotes: 0

Related Questions