比较两个Javascript数组并删除重复
如果它有另一个数组的元素,那么还有没有其他更好的方法可以从一个数组中删除重复的数据呢?
<script> var array1 = new Array("a","b","c","d","e","f"); var array2 = new Array("c","e"); for (var i = 0; i<array2.length; i++) { var arrlen = array1.length; for (var j = 0; j<arrlen; j++) { if (array2[i] == array1[j]) { array1 = array1.slice(0, j).concat(array1.slice(j+1, arrlen)); } } } alert(array1); </script>
array1 = array1.filter(function(val) { return array2.indexOf(val) == -1; });
或者,随着ES6的可用性:
array1 = array1.filter(val => !array2.includes(val));
filter()参考
indexOf()在这里引用
包括()在这里引用
使用Array.splice()
var array1 = ['1', '2', '3', '4', '5']; var array2 = ['4', '5']; var index; for (var i=0; i<array2.length; i++) { index = array1.indexOf(array2[i]); if (index > -1) { array1.splice(index, 1); } }
window.onload = function () { var array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']; var array2 = ['c', 'h', 'k']; var array3 = []; var SecondarrayIndexcount = 0; for (var i = 0; i < array1.length; i++) { for (var j = 0; j < array2.length; j++) { if (array1[i] !== array2[j]) { if (SecondarrayIndexcount === (array2.length - 1)) { array3.push(array1[i]); SecondarrayIndexcount = 0; break; } SecondarrayIndexcount++; } } } for (var i in array3) { alert(array3[i]); } } </script>