# JavaScript获取多个数组的交集简单实例

###### 分类 : 编程语言 | 发布时间 : 2018-04-21 09:06:21 | 浏览 : 0

具体思路为：先初始一个最小数组为A数组,元素个数最小的也是数组A的长度.然后再迭代各个数组,取得这几个数组长度最短的为最小长度,同时得到长度最短数组。然后,迭代最小数组与各个数组,开始比较元素相等,使用计数器来判断是否该元素在各个数组中都存在即为交集元素.
思路比较简单,但是可以实现多数组取得交集,代码如下：

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script>
function getValues(obj){
var values = "";
var l = obj.options.length;
for (var i=0; i<l; i++) {
if (i != (l-1)) {
values += obj.options(i).value + "_";
}
else {
values += obj.options(i).value;
}
}
return values;
}

function _test() {
var ids = getValues(document.all.aa);
var aa = _getIntersection(ids);
}

function _getIntersection(src) {
var tAry = src.split("_");
//最小数组
var minAry = null;
var min = tAry[0].split(",").length; //初始化第一个为长度最小的数组
minAry = tAry[0].split(",");
for (var i = 1, len = tAry.length; i<len; i++) {
var temp = tAry[i].split(",");
if (temp.length < min) {
min = temp.length;
minAry = temp;
}
}

var ret = '';
for (var i = 0, len = minAry.length; i<len; i++) {
var srcNum = parseInt(minAry[i]);
var counter = 0;
for (var j = 0, ll = tAry.length; j<ll; j++) {
var tt = tAry[j].split(",");
for (var k = 0, l = tt.length; k<l; k++) {
var tarNum = parseInt(tt[k]);
if (srcNum == tarNum) {
counter ++;
}
}
}
if (counter == tAry.length) {
ret += srcNum + ",";
}
}
ret = strSlice(ret, ',');
}

//去掉结尾分隔符
function strSlice(str, split){
if ((str!=null && str!="") && (split!=' '))
return ((str.charAt(str.length-1) == split) ? str.substring(0, str.length-1) : str);
else
return str;
}
</script>

<BODY>
<button onclick="javascript:_test();">测试</button>

<select name="aa" id="aa" size="6" multiple>
<OPTION value="10004,10005,10008,10009,10010,10018">测试1</OPTION>
<OPTION value="10004,10005,10006,10008,10009,10010,10018">测试2</OPTION>
<OPTION value="10004,10005,10006,10008,10009,10010,10018">测试3</OPTION>
<OPTION value="10004,10006,10008">测试4</OPTION>
<OPTION value="10004,10010,10018">测试5</OPTION>
</select>

</BODY>
</HTML>

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How do I replace a character at a particular index in JavaScript?