jQuery中是否有类似array_unique()的函数? [英] Is there a function like array_unique() in jQuery?

查看:67
本文介绍了jQuery中是否有类似array_unique()的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a select where i can get some values as array like ["1","2","3"]

在每次更改时,我运行以下代码来获取数组的结果,该结果与从select中获取的这些值相关联

On every change i run the following code to get a result of array which is connected to these values i get from 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个选项和结果数组后查看类型数组:

Here is my console log to let you see the type array after i selected 2 options and the results array:

["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中做到这一点.

As you see there is two times "4689 Leadership Award" and i dont want this to happen. In PHP i use the array_unique() function to eliminate these duplicated values but i dont know how to do it in jQuery.

推荐答案

尝试一下:

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

工作示例:

const startingArray = [1, 2, 2, 3, 2, 3, 3, 3];

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

const uniqueArray = unique(startingArray);

console.log(uniqueArray);

这篇关于jQuery中是否有类似array_unique()的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆