js 两个数组相减

var arr1 = ["", "100", "120", "125", "125", "130", "130"];

var arr2 = ["", "120", "125", "125", "130"];

请问如何求得两个数组之差?使得新数组为 arr3 = ["100","130"]

或则转化为处理两个字符串的问题:
var p1 = 100, 120, 125, 125, 130, 130;
var p2 = 120, 125, 125, 130;

求得两个字符串之差?使得新字符串为 p3 = 100,130;

补充: 要求根据元素(字符)个数相减

阅读 34.7k
7 个回答

不说废话,直接上代码

var arr1 = ["", "120", "125", "125", "130", "130", "130", "130", "130"];

var arr2 = ["", "120", "125", "130"];

for (var i = arr1.length - 1; i >= 0; i--) {
    a = arr1[i];
    for (var j = arr2.length - 1; j >= 0; j--) {
        b = arr2[j];
        if (a == b) {
            arr1.splice(i, 1);
            arr2.splice(j, 1);
            break;
        }
    }
}

console.log(arr1);  // ["125","130","130","130","130"]

var arr1 = [1, 2, 3]
var arr2 = [1, 3]
var arr3 = arr1.filter(el => !arr2.includes(el))

includes 是 es 6 的,也可以用下面的,箭头函数es6的,不行你就转成普通函数:

var arr3 = arr1.filter(el => !~arr2.indexOf(el))

用map(hashtable)的思想来解决。
思路:将第一个数组存入一个对象,这样就已经去重了;再把第二个数组中的元素当作key从对象中删除。
我大概写下代码:

var m = {};
arr1.forEach(function(al){m[al]=al;})
arr2.forEach(function(bl){delete m[bl];})
console.dir(Object.keys(m))
var arr1 = ["", "100", "120", "125", "125", "130", "130"];
var arr2 = ["", "120", "125", "125", "130"];
var arr3 = [];
arr1.forEach((a)=>{
    let c = arr2.findIndex(b=>a == b);
    if (c > -1) delete arr2[c];
    else arr3.push(a);
});
console.log(arr3)  //["100", "130"]

那么多的130,怎么知道你要怎么减?说说你的想法呀。。。

underscore

什么叫做数组之差?是向量相减?

推荐问题
宣传栏