jQuery中是否有类似于array_unique()的函数?
jQuery中是否有类似于array_unique()的函数?
这个问题已经有答案了:
我有一个select,可以获得一些值,例如[\"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 Leadership Award”,我不希望这种情况发生。 在PHP中,我使用array_unique()
函数消除这些重复值,但我不知道如何在jQuery中实现。
admin 更改状态以发布 2023年5月20日
尝试这个:\n
function unique(array){ return array.filter(function(el, index, arr) { return index == arr.indexOf(el); }); }
\n可行的示例:\n
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);