How to get unique values in an array

后端 未结 20 2343
情歌与酒
情歌与酒 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:37

    One Liner, Pure JavaScript

    With ES6 syntax

    list = list.filter((x, i, a) => a.indexOf(x) === i)

    x --> item in array
    i --> index of item
    a --> array reference, (in this case "list")
    

    With ES5 syntax

    list = list.filter(function (x, i, a) { 
        return a.indexOf(x) === i; 
    });
    

    Browser Compatibility: IE9+

提交回复
热议问题