2

I am studying algo & ds. And there are many times we use the map. For example, Leetcode 1 problem, two Sum. We can solve it as below.

var twoSum = function(nums, target) {
    let map = new Map();
    
    for (let i = 0; i < nums.length; i ++) {
        if (map[nums[i]] >= 0) {
            return [map[nums[i]], i]
        }
        map[target-nums[i]] = i
    }
    return [-1, -1];
};

But I am not sure what's the difference between

let map = {};

and

let map = new Map();

Please enlighten me.

Thank you.

5
  • 5
    Does this answer your question? Map vs Object in JavaScript Commented Mar 23, 2021 at 4:08
  • @dalelandry Thanks Dale!! that section totally answers my question. Thanks a lot. So for example, the solution for two sum, I don't iterate map or use any map property. So it's better to use let map = {}? Commented Mar 23, 2021 at 4:09
  • Yes, stick with objects, in particular maps are not easily serializable with JSON.stringify(). You might find them interesting for fast timeseries data, FIFO operations, or for seeking for pure performance operations and memory footprint. (But then i do personnaly prefer pure integers arrays^ and associative arrays) Commented Mar 23, 2021 at 4:29
  • @teemothy No, it's better to use the Map methods :-) Commented Mar 23, 2021 at 6:50
  • @Bergi would you please describe lil more why Map methods are better? Thanks!! Commented Mar 23, 2021 at 7:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.