2

I've only been learning javascript for a couple weeks and this is my first post so apologies if my question isn't very clear. I'm using the forEach method in Map's prototype to loop through a map of streets and their lengths. In the prototype of the Map the key value pairs are correct i.e.:

0: {"amesSt" => 500} key: "amesSt" value: 500)

However, the entries seem to flip when taken as arguments in forEach, meaning the key becomes the value and value becomes the key.

console.log('==============STREET REPORT==============')

// key = 'amesSt', value = 500
const streetLengths = new Map();
streetLengths.set('amesSt', 500);
streetLengths.set('bentonSt', 1200);
streetLengths.set('chaseSt', 750);
streetLengths.set('depewSt', 200);

console.log(streetLengths);

// classify streets
    function streetClass(key, value) {

    if (value < 250) {
        console.log(`${key} Street is classified as small`);
    } else if (value >= 250 && value < 600) {
        console.log(`${key} Street is classified as normal`);
    } else if (value >= 600 && value < 1000) {
        console.log(`${key} Street is classified as big`);
    } else if (value >= 1000){
        console.log(`${key} Street is classified as huge`);
    } else{
        console.log('Normal');
    };  
};

console.log('Size classification:');

//key = 500, value = 'amesSt'
streetLengths.forEach((key, value) => {

    streetClass(key, value);
});

I would like for the key value to be stored in the key variable in the forEach loop and value to be stored in the value variable. I'm currently using VS Code v1.34.0. Thanks in advance for the help!

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
moreLosty
  • 23
  • 4

2 Answers2

2

As you can see in the docs: Javascript forEach(), the forEach method receives a callback as first parameter, and this callback could receive three parameters: currentValue, index, array, in this order.

So you are inverting the parameters order. It should be:

streetLengths.forEach((value, key) => {

    streetClass(key, value);
});
Pedro leal
  • 174
  • 2
  • 8
0

When we iterate over Map using forEach, the first argument is value,second is keyiterating over Map using forEach

In your function you are considering first argument as 'key'

shikhar
  • 110
  • 10