javascript数组去重
数组去重处理函数:
function uniqueArray(a) { var temp = new Array(); for (var i = 0; i < a.length; i++) { if (!contains(temp, a[i])) { temp.length += 1; temp[temp.length - 1] = a[i]; } } return temp; } function contains(a, e) { for (j = 0; j < a.length; j++) if (a[j] == e) return true; return false; }
使用例子:
/** * @create: nelson * @Eliminate duplicate items from qListview * @eliminateDuplicate * @调用方式 $("#container").eliminateDuplicateVal(qListview); */ $.fn.extend({ eliminateDuplicateVal: function (qListview) { var This = $(this); var That = This.find(qListview); var _resultPanel = This.find("> .itemp_check_no strong"); var _loading = This.find("> .loading"); function init() { var html = ""; var strFilterArr = new Array(); var _select = This.find("> .item_check_field"); That.find(">thead .rgHeader").each(function () {//拼select的option html字符串 var str = $(this).text().trim(); html += '<option>' + str + '</option>'; strFilterArr.push(str); }); if (html != "") { html = '<option></option>' + html; _select.html(html); if (That.find(">tbody .rgNoRecords").length != 1) { _resultPanel.html(That.find(">tbody>tr").length);//初始化记录数 This.find("> .item_check_btn").click(function () { _loading.css("display", "inline-block");//显示loading gif动画图片 setTimeout(function () { var strFilter = _select.children("option:selected").text(); if (strFilter != "") { var key = strFilterArr.indexOf(strFilter); var strResultArr = new Array(); That.find(">tbody>tr").each(function () { $(this).css("display", "none");//全部行隐藏 strResultArr.push($(this).find("td:eq(" + key + ")").text().trim());//建结果数组 }); strResultArr = uniqueArray(strResultArr);//去重 $.each(strResultArr, function (k, strValue) { That.find(">tbody>tr").each(function () { //显示过滤后的内容行 var self = $(this); if (self.find("td:eq(" + key + ")").text().trim() == strValue) { self.css("display", "table-row"); return false; } }); }); _resultPanel.html(strResultArr.length); } //setTimeout(function () { _loading.css("display", "none"); }, 1000); return false; }); } else { This.find("> .item_check_btn").click(function () { alert("请先在下方进行搜索再执行本操作!"); return false; }); } } } function uniqueArray(a) { var temp = new Array(); for (var i = 0; i < a.length; i++) { if (!contains(temp, a[i])) { temp.length += 1; temp[temp.length - 1] = a[i]; } } return temp; } function contains(a, e) { for (j = 0; j < a.length; j++) if (a[j] == e) return true; return false; } init(); } });