在jQuery中是否有类似array_unique()的函数?

时间:2014-08-27 14:42:00

标签: javascript php jquery arrays

我有一个选择,我可以在其中获取一些值,如["1","2","3"]

这样的数组

在每次更改时,我运行以下代码以获得连接到这些值的数组的结果我从select

$('#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"] ------------------- 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 个答案:

答案 0 :(得分:13)

试试这个:

function unique(array){
    return array.filter(function(el, index, arr) {
        return index == arr.indexOf(el);
    });
}