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.

teemothy
  • 21
  • 2
  • 5
    Does this answer your question? [Map vs Object in JavaScript](https://stackoverflow.com/questions/18541940/map-vs-object-in-javascript) – dale landry Mar 23 '21 at 04: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 = {}? – teemothy Mar 23 '21 at 04: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) – NVRM Mar 23 '21 at 04:29
  • @teemothy No, it's better to use the `Map` methods :-) – Bergi Mar 23 '21 at 06:50
  • @Bergi would you please describe lil more why Map methods are better? Thanks!! – teemothy Mar 23 '21 at 07:15

0 Answers0