简体   繁体   English

如何获取JavaScript中两个arrays对象的区别

[英]How to get the difference between two arrays of objects in JavaScript

I have two result sets like this:我有两个这样的结果集:

// Result 1
[
    { value: "0", display: "Jamsheer" },
    { value: "1", display: "Muhammed" },
    { value: "2", display: "Ravi" },
    { value: "3", display: "Ajmal" },
    { value: "4", display: "Ryan" }
]

// Result 2
[
    { value: "0", display: "Jamsheer" },
    { value: "1", display: "Muhammed" },
    { value: "2", display: "Ravi" },
    { value: "3", display: "Ajmal" },
]

The final result I need is the difference between these arrays – the final result should be like this:我需要的最终结果是这些 arrays 之间的差——最终结果应该是这样的:

[{ value: "4", display: "Ryan" }]

Is it possible to do something like this in JavaScript?是否可以在 JavaScript 中做这样的事情?

Using only native JS, something like this will work:仅使用本机 JS,这样的事情将起作用:

 const a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"}, { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]; const b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]; // A comparer used to determine if two entries are equal. const isSameUser = (a, b) => a.value == b.value && a.display == b.display; // Get items that only occur in the left array, // using the compareFunction to determine equality. const onlyInLeft = (left, right, compareFunction) => left.filter(leftValue => !right.some(rightValue => compareFunction(leftValue, rightValue))); const onlyInA = onlyInLeft(a, b, isSameUser); const onlyInB = onlyInLeft(b, a, isSameUser); const result = [...onlyInA, ...onlyInB]; console.log(result);

For those who like one-liner solutions in ES6, something like this:对于那些喜欢 ES6 中的单行解决方案的人来说,像这样:

 const arrayOne = [ { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" }, { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" }, { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" }, { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" }, { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" }, ]; const arrayTwo = [ { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"}, { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"}, { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"}, { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"}, ]; const results = arrayOne.filter(({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1)); console.log(results);

You could use Array.prototype.filter() in combination with Array.prototype.some() .您可以将Array.prototype.filter()Array.prototype.some()结合使用。

Here is an example (assuming your arrays are stored in the variables result1 and result2 ):这是一个示例(假设您的数组存储在变量result1result2 ):

//Find values that are in result1 but not in result2
var uniqueResultOne = result1.filter(function(obj) {
    return !result2.some(function(obj2) {
        return obj.value == obj2.value;
    });
});

//Find values that are in result2 but not in result1
var uniqueResultTwo = result2.filter(function(obj) {
    return !result1.some(function(obj2) {
        return obj.value == obj2.value;
    });
});

//Combine the two arrays of unique entries
var result = uniqueResultOne.concat(uniqueResultTwo);
import differenceBy from 'lodash/differenceBy'

const myDifferences = differenceBy(Result1, Result2, 'value')

This will return the difference between two arrays of objects, using the key value to compare them.这将返回区别对象的两个阵列之间,使用该密钥value对它们进行比较。 Note two things with the same value will not be returned, as the other keys are ignored.请注意,不会返回具有相同值的两个东西,因为其他键将被忽略。

This is a part of lodash .这是lodash的一部分。

I take a slightly more general-purpose approach, although similar in ideas to the approaches of both @Cerbrus and @Kasper Moerch .我采用了一种更通用的方法,尽管在想法上与@Cerbrus@Kasper Moerch的方法相似 I create a function that accepts a predicate to determine if two objects are equal (here we ignore the $$hashKey property, but it could be anything) and return a function which calculates the symmetric difference of two lists based on that predicate:我创建了一个函数,它接受一个谓词来确定两个对象是否相等(这里我们忽略$$hashKey属性,但它可以是任何东西)并返回一个函数,该函数根据该谓词计算两个列表的对称差异:

a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"},  { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]
b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]

var makeSymmDiffFunc = (function() {
    var contains = function(pred, a, list) {
        var idx = -1, len = list.length;
        while (++idx < len) {if (pred(a, list[idx])) {return true;}}
        return false;
    };
    var complement = function(pred, a, b) {
        return a.filter(function(elem) {return !contains(pred, elem, b);});
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

var myDiff = makeSymmDiffFunc(function(x, y) {
    return x.value === y.value && x.display === y.display;
});

var result = myDiff(a, b); //=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

It has one minor advantage over Cerebrus's approach (as does Kasper Moerch's approach) in that it escapes early;与 Cerebrus 的方法(卡斯帕·莫尔奇的方法一样)相比,它有一个小优势,即它可以提前逃脱; if it finds a match, it doesn't bother checking the rest of the list.如果找到匹配项,则不会检查列表的其余部分。 If I had a curry function handy, I would do this a little differently, but this works fine.如果我手头有一个curry函数,我会做一些不同的事情,但这工作正常。

Explanation解释

A comment asked for a more detailed explanation for beginners.一个评论要求为初学者提供更详细的解释。 Here's an attempt.这是一个尝试。

We pass the following function to makeSymmDiffFunc :我们将以下函数传递给makeSymmDiffFunc

function(x, y) {
    return x.value === y.value && x.display === y.display;
}

This function is how we decide that two objects are equal.这个函数是我们决定两个对象相等的方式。 Like all functions that return true or false , it can be called a "predicate function", but that's just terminology.像所有返回truefalse函数一样,它可以称为“谓词函数”,但这只是术语。 The main point is that makeSymmDiffFunc is configured with a function that accepts two objects and returns true if we consider them equal, false if we don't.要点是makeSymmDiffFunc配置了一个函数,该函数接受两个对象,如果我们认为它们相等则返回true否则返回false

Using that, makeSymmDiffFunc (read "make symmetric difference function") returns us a new function:使用它, makeSymmDiffFunc (读作“生成对称差分函数”)返回一个新函数:

        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };

This is the function we will actually use.这是我们将实际使用的函数。 We pass it two lists and it finds the elements in the first not in the second, then those in the second not in the first and combine these two lists.我们向它传递两个列表,它在第一个而不是第二个中找到元素,然后在第二个中而不是第一个中找到元素,然后组合这两个列表。

Looking over it again, though, I could definitely have taken a cue from your code and simplified the main function quite a bit by using some :不过,再看一遍,我肯定可以从您的代码中得到提示,并通过使用some大大简化 main 函数:

var makeSymmDiffFunc = (function() {
    var complement = function(pred, a, b) {
        return a.filter(function(x) {
            return !b.some(function(y) {return pred(x, y);});
        });
    };
    return function(pred) {
        return function(a, b) {
            return complement(pred, a, b).concat(complement(pred, b, a));
        };
    };
}());

complement uses the predicate and returns the elements of its first list not in its second. complement使用谓词并返回其第一个列表的元素,而不是第二个列表中的元素。 This is simpler than my first pass with a separate contains function.这比我第一次使用单独的contains函数更简单。

Finally, the main function is wrapped in an immediately invoked function expression ( IIFE ) to keep the internal complement function out of the global scope.最后, main 函数被包装在一个立即调用的函数表达式 ( IIFE ) 中,以将内部complement函数保持在全局范围之外。


Update, a few years later几年后更新

Now that ES2015 has become pretty well ubiquitous, I would suggest the same technique, with a lot less boilerplate:现在 ES2015 已经变得非常普遍,我建议使用相同的技术,但样板文件要少得多:

const diffBy = (pred) => (a, b) => a.filter(x => !b.some(y => pred(x, y)))
const makeSymmDiffFunc = (pred) => (a, b) => diffBy(pred)(a, b).concat(diffBy(pred)(b, a))

const myDiff = makeSymmDiffFunc((x, y) => x.value === y.value && x.display === y.display)

const result = myDiff(a, b)
//=>  {value="a63a6f77-c637-454e-abf2-dfb9b543af6c", display="Ryan"}

I think the @Cerbrus solution is spot on.我认为@Cerbrus 解决方案是正确的。 I have implemented the same solution but extracted the repeated code into it's own function (DRY).我已经实现了相同的解决方案,但将重复的代码提取到它自己的函数中(DRY)。

 function filterByDifference(array1, array2, compareField) {
  var onlyInA = differenceInFirstArray(array1, array2, compareField);
  var onlyInb = differenceInFirstArray(array2, array1, compareField);
  return onlyInA.concat(onlyInb);
}

function differenceInFirstArray(array1, array2, compareField) {
  return array1.filter(function (current) {
    return array2.filter(function (current_b) {
        return current_b[compareField] === current[compareField];
      }).length == 0;
  });
}

You can create an object with keys as the unique value corresponding for each object in array and then filter each array based on existence of the key in other's object.您可以创建一个对象,将键作为数组中每个对象对应的唯一值,然后根据其他对象中键的存在来过滤每个数组。 It reduces the complexity of the operation.它降低了操作的复杂性。

ES6 ES6

 let a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"}, { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]; let b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]; let valuesA = a.reduce((a,{value}) => Object.assign(a, {[value]:value}), {}); let valuesB = b.reduce((a,{value}) => Object.assign(a, {[value]:value}), {}); let result = [...a.filter(({value}) => !valuesB[value]), ...b.filter(({value}) => !valuesA[value])]; console.log(result);

ES5 ES5

 var a = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal"}, { value:"a63a6f77-c637-454e-abf2-dfb9b543af6c", display:"Ryan"}]; var b = [{ value:"4a55eff3-1e0d-4a81-9105-3ddd7521d642", display:"Jamsheer", $$hashKey:"008"}, { value:"644838b3-604d-4899-8b78-09e4799f586f", display:"Muhammed", $$hashKey:"009"}, { value:"b6ee537a-375c-45bd-b9d4-4dd84a75041d", display:"Ravi", $$hashKey:"00A"}, { value:"e97339e1-939d-47ab-974c-1b68c9cfb536", display:"Ajmal", $$hashKey:"00B"}]; var valuesA = a.reduce(function(a,c){a[c.value] = c.value; return a; }, {}); var valuesB = b.reduce(function(a,c){a[c.value] = c.value; return a; }, {}); var result = a.filter(function(c){ return !valuesB[c.value]}).concat(b.filter(function(c){ return !valuesA[c.value]})); console.log(result);

In addition, say two object array with different key value另外,说两个key value不同的对象数组

// Array Object 1
const arrayObjOne = [
    { userId: "1", display: "Jamsheer" },
    { userId: "2", display: "Muhammed" },
    { userId: "3", display: "Ravi" },
    { userId: "4", display: "Ajmal" },
    { userId: "5", display: "Ryan" }
]

// Array Object 2
const arrayObjTwo =[
    { empId: "1", display: "Jamsheer", designation:"Jr. Officer" },
    { empId: "2", display: "Muhammed", designation:"Jr. Officer" },
    { empId: "3", display: "Ravi", designation:"Sr. Officer" },
    { empId: "4", display: "Ajmal", designation:"Ast. Manager" },
]

You can use filter in es5 or native js to substract two array object.可以在es5native js使用filter来减去两个数组对象。

//Find data that are in arrayObjOne but not in arrayObjTwo
var uniqueResultArrayObjOne = arrayObjOne.filter(function(objOne) {
    return !arrayObjTwo.some(function(objTwo) {
        return objOne.userId == objTwo.empId;
    });
});

In ES6 you can use Arrow function with Object destructuring of ES6 .ES6您可以使用箭头函数和ES6 对象解构

const ResultArrayObjOne = arrayObjOne.filter(({ userId: userId }) => !arrayObjTwo.some(({ empId: empId }) => empId === userId));

console.log(ResultArrayObjOne);

I found this solution using filter and some.我使用过滤器和一些找到了这个解决方案。

 resultFilter = (firstArray, secondArray) => { return firstArray.filter(firstArrayItem => !secondArray.some( secondArrayItem => firstArrayItem._user === secondArrayItem._user ) ); };

you can do diff a on b and diff b on a, then merge both results你可以在 b 上做 diff a,在 a 上做 diff b,然后合并两个结果

 let a = [ { value: "0", display: "Jamsheer" }, { value: "1", display: "Muhammed" }, { value: "2", display: "Ravi" }, { value: "3", display: "Ajmal" }, { value: "4", display: "Ryan" } ] let b = [ { value: "0", display: "Jamsheer" }, { value: "1", display: "Muhammed" }, { value: "2", display: "Ravi" }, { value: "3", display: "Ajmal" } ] // b diff a let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm))); // a diff b let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm))); // show merge console.log([...resultA, ...resultB]);

 let obj1 =[ { id: 1, submenu_name: 'login' }, { id: 2, submenu_name: 'Profile',}, { id: 3, submenu_name: 'password', }, { id: 4, submenu_name: 'reset',} ] ; let obj2 =[ { id: 2}, { id: 3 }, ] ; // Need Similar obj const result1 = obj1.filter(function(o1){ return obj2.some(function(o2){ return o1.id == o2.id; // id is unnique both array object }); }); console.log(result1); // Need differnt obj const result2 = obj1.filter(function(o1){ return !obj2.some(function(o2){ // for diffrent we use NOT (!) befor obj2 here return o1.id == o2.id; // id is unnique both array object }); }); console.log(result2);

Most of the observed code does not examine the whole object and only compares the value of a particular method.大多数观察到的代码不会检查整个 object,而只会比较特定方法的值。 This solution is the same, except that you can specify that method yourself.这个解决方案是一样的,只是你可以自己指定那个方法。

Here is an example:这是一个例子:

const arr1 = [
   {
      id: 1,
      name: "Tom",
      scores: {
         math: 80,
         science: 100
      }
   },
   {
      id: 2,
      name: "John",
      scores: {
         math: 50,
         science: 70
      }
   }
];
const arr2 = [
   {
      id: 1,
      name: "Tom",
      scores: {
         math: 80,
         science: 70
      }
   }
];

function getDifference(array1, array2, attr) {
  return array1.filter(object1 => {
    return !array2.some(object2 => {
      return eval("object1." + attr + " == object2." + attr);
    });
  });
}

// 👇️ [{id: 2, name: 'John'...
console.log(getDifference(arr1, arr2, "id"));

// 👇️ [{id: 2, name: 'John'...
console.log(getDifference(arr1, arr2, "scores.math"));

// 👇️ [{id: 1, name: 'Tom'...
console.log(getDifference(arr1, arr2, "scores.science"));

Most of answers here are rather complex, but isn't logic behind this quite simple?这里的大多数答案都相当复杂,但这背后的逻辑是不是很简单?

  1. check which array is longer and provide it as first parameter (if length is equal, parameters order doesnt matter)检查哪个数组更长并将其作为第一个参数提供(如果长度相等,则参数顺序无关紧要)
  2. Iterate over array1.迭代 array1。
  3. For current iteration element of array1 check if it is present in array2对于 array1 的当前迭代元素,检查它是否存在于 array2 中
  4. If it is NOT present, than如果它不存在,则比
  5. Push it to 'difference' array将其推送到“差异”数组
const getArraysDifference = (longerArray, array2) => {
  const difference = [];

  longerArray.forEach(el1 => {      /*1*/
    el1IsPresentInArr2 = array2.some(el2 => el2.value === el1.value); /*2*/

    if (!el1IsPresentInArr2) { /*3*/
      difference.push(el1);    /*4*/
    }
  });

  return difference;
}

O(n^2) complexity. O(n^2) 复杂度。

I prefer map object when it comes to big arrays.当涉及到大数组时,我更喜欢 map 对象。

 // create tow arrays array1 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)})) array2 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)})) // calc diff with some function console.time('diff with some'); results = array2.filter(({ value: id1 }) => array1.some(({ value: id2 }) => id2 === id1)); console.log('diff results ',results.length) console.timeEnd('diff with some'); // calc diff with map object console.time('diff with map'); array1Map = {}; for(const item1 of array1){ array1Map[item1.value] = true; } results = array2.filter(({ value: id2 }) => array1Map[id2]); console.log('map results ',results.length) console.timeEnd('diff with map');

Having:拥有:

const array = [{id:3, name:'xx'} , {id:7, name:'yy'}, {id:9, name:'zz'}];
const array2 =[3,4,5];//These are a group of ids

I made a function that removes the objects from array that matches de ids within array2, like this:我制作了一个 function,它从数组中删除了与 array2 中的 de id 匹配的对象,如下所示:

export const aFilter = (array, array2) => {
   
   array2.forEach(element => {
      array = array.filter(item=> item.id !== element);
   });
   return array;
}

After calling the function we should have the array with no object wit id = 3调用 function 后,我们应该得到没有 object 且 id = 3 的数组

const rta = aFilter(array, array2);
//rta should be = [{id:7, name:'yy'}, {id:9, name:'zz'}];

It worked for me, and was pretty easy它对我有用,而且非常简单

I've made a generalized diff that compare 2 objects of any kind and can run a modification handler gist.github.com/bortunac "diff.js" an ex of using :我做了一个通用的 diff 比较任​​何类型的 2 个对象,并且可以运行一个修改处理程序gist.github.com/bortunac "diff.js"一个 ex 使用:

old_obj={a:1,b:2,c:[1,2]}
now_obj={a:2 , c:[1,3,5],d:55}

so property a is modified, b is deleted, c modified, d is added所以属性a被修改,b被删除,c被修改,d被添加

var handler=function(type,pointer){
console.log(type,pointer,this.old.point(pointer)," | ",this.now.point(pointer)); 

} }

now use like现在使用像

df=new diff();
df.analize(now_obj,old_obj);
df.react(handler);

the console will show控制台将显示

mdf ["a"]  1 | 2 
mdf ["c", "1"]  2 | 3 
add ["c", "2"]  undefined | 5 
add ["d"]  undefined | 55 
del ["b"]  2 | undefined 

Most generic and simple way:最通用和最简单的方法:

findObject(listOfObjects, objectToSearch) {
    let found = false, matchingKeys = 0;
    for(let object of listOfObjects) {
        found = false;
        matchingKeys = 0;
        for(let key of Object.keys(object)) {
            if(object[key]==objectToSearch[key]) matchingKeys++;
        }
        if(matchingKeys==Object.keys(object).length) {
            found = true;
            break;
        }
    }
    return found;
}

get_removed_list_of_objects(old_array, new_array) {
    // console.log('old:',old_array);
    // console.log('new:',new_array);
    let foundList = [];
    for(let object of old_array) {
        if(!this.findObject(new_array, object)) foundList.push(object);
    }
    return foundList;
}

get_added_list_of_objects(old_array, new_array) {
    let foundList = [];
    for(let object of new_array) {
        if(!this.findObject(old_array, object)) foundList.push(object);
    }
    return foundList;
}

JavaScript has Maps, that provide O(1) insertion and lookup time. JavaScript 有 Maps,它提供 O(1) 插入和查找时间。 Therefore this can be solved in O(n) (and not O(n²) as all the other answers do).因此,这可以用 O(n) 解决(而不是像所有其他答案那样用 O(n²) 解决)。 For that, it is necessary to generate a unique primitive (string / number) key for each object.为此,有必要为每个对象生成唯一的原始(字符串/数字)键。 One could JSON.stringify , but that's quite error prone as the order of elements could influence equality:可以使用JSON.stringify ,但这很容易出错,因为元素的顺序可能会影响相等性:

 JSON.stringify({ a: 1, b: 2 }) !== JSON.stringify({ b: 2, a: 1 })

Therefore, I'd take a delimiter that does not appear in any of the values and compose a string manually:因此,我会采用一个未出现在任何值中的分隔符并手动组合一个字符串:

const toHash = value => value.value + "@" + value.display;

Then a Map gets created.然后创建一个 Map。 When an element exists already in the Map, it gets removed, otherwise it gets added.当 Map 中已经存在一个元素时,它会被删除,否则会被添加。 Therefore only the elements that are included odd times (meaning only once) remain.因此,仅包含奇数次(即仅一次)的元素保留。 This will only work if the elements are unique in each array:这只适用于每个数组中的元素都是唯一的:

const entries = new Map();

for(const el of [...firstArray, ...secondArray]) {
  const key = toHash(el);
  if(entries.has(key)) {
    entries.delete(key);
  } else {
    entries.set(key, el);
  }
}

const result = [...entries.values()];

 const firstArray = [ { value: "0", display: "Jamsheer" }, { value: "1", display: "Muhammed" }, { value: "2", display: "Ravi" }, { value: "3", display: "Ajmal" }, { value: "4", display: "Ryan" } ] const secondArray = [ { value: "0", display: "Jamsheer" }, { value: "1", display: "Muhammed" }, { value: "2", display: "Ravi" }, { value: "3", display: "Ajmal" }, ]; const toHash = value => value.value + "@" + value.display; const entries = new Map(); for(const el of [...firstArray, ...secondArray]) { const key = toHash(el); if(entries.has(key)) { entries.delete(key); } else { entries.set(key, el); } } const result = [...entries.values()]; console.log(result);

I came across this question while searching for a way to pick out the first item in one array that does not match any of the values in another array and managed to sort it out eventually with array.find() and array.filter() like this我在寻找一种方法来挑选一个数组中与另一个数组中的任何值都不匹配的第一个项目时遇到了这个问题,并最终使用 array.find() 和 array.filter() 对其进行了排序这个

var carList= ['mercedes', 'lamborghini', 'bmw', 'honda', 'chrysler'];
var declinedOptions = ['mercedes', 'lamborghini'];

const nextOption = carList.find(car=>{
    const duplicate = declinedOptions.filter(declined=> {
      return declined === car
    })
    console.log('duplicate:',duplicate) //should list out each declined option
    if(duplicate.length === 0){//if theres no duplicate, thats the nextOption
      return car
    }
})

console.log('nextOption:', nextOption);
//expected outputs
//duplicate: mercedes
//duplicate: lamborghini
//duplicate: []
//nextOption: bmw

if you need to keep fetching an updated list before cross-checking for the next best option this should work well enough :)如果您需要在交叉检查下一个最佳选项之前继续获取更新的列表,这应该足够好:)

最简单的方法可能是使用过滤器一些一起使用请参考下面的链接DifferenceInTwoArrayOfObjectInSimpleWay

@atheane response: fork : @atheane回应:分叉

 const newList = [ { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" }, { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" }, { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi2" }, { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" }, ]; const oldList = [ { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"}, { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"}, { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"}, { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"}, ]; const resultsAdd = newList.filter(({ value: id1 }) =>.oldList:some(({ value; id2 }) => id2 === id1)). const resultsRemove = oldList:filter(({ value. id1 }) =>:newList;some(({ value. id2 }) => id2 === id1)): const resultsUpdate = newList,filter(({ value. id1. ..:rest1 }) => oldList,some(({ value. id2. ...rest2 }) => id2 === id1 && JSON;stringify(rest1).== JSON,stringify(rest2))); console.log("added", resultsAdd); console.log("removed", resultsRemove); console.log("updated", resultsUpdate);

If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this.如果您愿意使用外部库,您可以在 underscore.js 中使用 _.difference 来实现这一点。 _.difference returns the values from array that are not present in the other arrays. _.difference 返回数组中不存在于其他数组中的值。

_.difference([1,2,3,4,5][1,4,10])

==>[2,3,5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM