关于javascript:在jQuery中是否有类似array_unique()的函数?

Is there a function like array_unique() in jQuery?

本问题已经有最佳答案,请猛点这里访问。

我有一个选择,在这里我可以得到一些值,比如数组["1","2","3"]

每次更改时,我都会运行以下代码来获取数组的结果,该数组与从select中获取的值相连接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
$('#event-courses-type').on('change',function(){

    type = $('#event-courses-type').val();

    console.log(type);

    var var1 = ["4689 Leadership Award","UKCC Level 1","UKCC Level 2","UKCC Level 3","UKCC Level 4","Old WHU Award","None at present"];
    var var2 = ["4689 Leadership Award","GB-wide Level 1","Old Level 1 (Pre January 2012)","Level 2","Level 3","EHF","FIH","None at present"];

    var var5 = ["D32/33","A1 Assessor","CTS","IAPS","PTLLS","AVRA","Umpire Educator Training","Umpire Assessor Training"];
    var var6 = ["D32/33","A1 Assessor","CTS","IAPS","PTLLS","AVRA","Umpire Educator Training","Umpire Assessor Training"];

    var results = [];

    if ($.inArray("1",type) != -1) {
        var results = $.merge(var1, results);
    }
    if ($.inArray("2",type) != -1) {
        var results = $.merge(var2, results);
    }
    if ($.inArray("5",type) != -1) {
        var results = $.merge(var5, results);
    }
    if ($.inArray("6",type) != -1) {
        var results = $.merge(var6, results);
    }

    console.log(results);
)};

下面是我的控制台日志,让您在选择了2个选项和结果数组后看到类型数组:

1
2
3
["1","2"] ------------------- add_event.php:802

["4689 Leadership Award","GB-wide Level 1","Old Level 1 (Pre January 2012)","Level 2","Level 3","EHF","FIH","None at present","4689 Leadership Award","UKCC Level 1","UKCC Level 2","UKCC Level 3","UKCC Level 4","Old WHU Award","None at present"]

正如你所看到的,有两次"4689领导力奖",我不希望这发生。在PHP中,我使用array_unique()函数来消除这些重复的值,但我不知道如何在jquery中实现。


试试这个:

1
2
3
4
5
function unique(array){
    return array.filter(function(el, index, arr) {
        return index == arr.indexOf(el);
    });
}