How to get unique values in an array

后端 未结 20 1923
情歌与酒
情歌与酒 2020-11-22 14:02

How can I get a list of unique values in an array? Do I always have to use a second array or is there something similar to java\'s hashmap in JavaScript?

I am going

20条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 14:55

    If you don't need to worry so much about older browsers, this is exactly what Sets are designed for.

    The Set object lets you store unique values of any type, whether primitive values or object references.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

    const set1 = new Set([1, 2, 3, 4, 5, 1]);
    // returns Set(5) {1, 2, 3, 4, 5}
    

提交回复
热议问题