Differences and advantages: Set and Map against Array and Object

0

Reading about ES6 and its characteristics, I wonder about:

  • What is the advantage of Map against an Object ?
  • What is the advantage of Set against an Array ?
  • I understand that both are for data collections, but why not use the primitive data instead?

    References (theoretical) that I have consulted:

    asked by Chofoteddy 10.12.2018 в 23:31
    source

    1 answer

    2

    I quote the same sources you provided:

    Set vs Array:

    Set objects are collections of values. You can iterate its elements in the order of their insertion. A value in a Set can only be once ; This one is unique in the Set collection.

    Seen with an example:

    var arr = [1, 2, 3];
    var set = new Set(arr);
    console.log(set); // {1,2,3}
    
    
    var arr = [1, 2, 1];
    var set = new Set(arr);
    console.log(set); // {1,2}
    

    Map vs Object

    Objects are similar to Maps in that both allow you to set keys to values, recover those values, delete keys, and detect if there is something stored in a certain key. Because of this, Objects have historically been used as Maps; however, there are important differences between Objects and Maps that make it better to use a Map in most cases

    • The keys of a Object are Strings and Symbols , while for Map they can be of any type, including functions, objects and any other primitive type. You can easily know the size of a Map using the size property, while the number of properties in an Object has to be manually deternminated.

    • A Map is a iterable which allows you to iterate directly over it, whereas if you want to iterate over a Object we need to first obtain the keys in some way and then iterate over it.

    • A Object has a prototype, so there are default keys on your map that can collide with your passwords if you are not careful. In the ES5 standard this can be avoided by using mapa = Object.create(null) , but this is rarely done.

    answered by 11.12.2018 / 00:27
    source