Using Map() in JavaScript

Sean Ransonette
2 min readNov 6, 2021

In my effort to be hired for my first software engineering job I have been practicing algorithms. Initially I have been talking bad about them but I am beginning to understand how they are useful. While truth be told they can be annoying, they are making me look into different ways to solve problems. My most recent favorite was Map() that I used while solving 2 sum.

Now just a quick explanation of 2 sum.

Basically you need to iterate through the array of numbers and return the two numbers that equal the target value. In the case of the example it is 2 and 7.

Map() makes this very manageable. What Map() does is it creates a new array when called on an already existing array, and holds results of a function called on an the elements in the initial array.

Here is a great example of what I mean.

For my 2 sum solution

I set a variable of map to equal new Map() and using a for let loop iterating through the original array. I also had to set some more variables that I can use for my if statement. If statement reads if the map array has num2, which is target-num1, then return the number in the map array and num2. If not the set num1 to the map array and keep iterating.

--

--