js简单算法如何去除一个数组中与另一个数组中的值相同的元素

如题所述

第1个回答  2017-10-08
var arr1 = [1,3,5,7,9];
var arr2 = [1,2,3,4,5,6,7,8,9];
console.log(arr1);
console.log(arr2);

for (var i = 0; i < arr2.length; i++){
    for (var j = 0; j < arr1.length; j++){
    
        if (arr2[i] == arr1[j]){
            arr2.splice(i,1);
        }
    }
}
console.log(arr2);

arr2是要去除与另一个数组中的值相同的数组, 如果把arr2和arr1互换, 前后两者结果如图:

第2个回答  2017-10-03
codewars上面6kyu的算法题,下面是算法题的英文简介

Your goal in this kata is to implement an difference function, which subtracts one list from another.
It should remove all values from list a, which are present in listb.
difference([1,2],[1]) == [2]

If a value is present in b, all of its occurrences must be removed from the other:
difference([1,2,2,2,3],[2]) == [1,3]

以下是我的解答,可以作为参考

[html] view plain copy
function array_diff(a, b) {
for(var i=0;i<b.length;i++)
{
for(var j=0;j<a.length;j++)
{
if(a[j]==b[i]){
a.splice(j,1);
j=j-1;
}
}
}
return a;
}本回答被提问者采纳