简体   繁体   English

javascript 中的数组差异

[英]array difference in javascript

I know this will be so simple but I am trying this for two days so I finally decided to take help from you guys... I have tried this probably the same question as mine but it is not giving me the answer.我知道这会很简单,但我尝试了两天,所以我终于决定向你们寻求帮助......我已经尝试过这个可能与我的问题相同的问题,但它没有给我答案。

ok so these are the two array好的,这是两个数组

a = [{toNumber: "123", message: "Hi Deep "}, {toNumber: "321", message: "Test1"}]
b = [{toNumber: "321", message: "Test2"}, {toNumber: "123", message: "Hi Deep "}]

What I want is我想要的是

diff = [{toNumber: "321", message: "Test2"}]

so quick help would be much appriciated.如此快速的帮助将非常受欢迎。

So with your code you need to look at the other object and see if it has any keys that match.因此,使用您的代码,您需要查看其他 object 并查看它是否有任何匹配的键。 If it matches, you need to see if the message matches.如果匹配,则需要查看消息是否匹配。 So you can make a look up object that has the list of ids.因此,您可以查找具有 id 列表的 object。 You can than loop over your second array and see if they march.你可以遍历你的第二个数组,看看他们是否行进。

 var a = [ {toNumber: "123", message: "Hi Deep "}, {toNumber: "321", message: "Test1"} ] var b = [ {toNumber: "321", message: "Test2"}, {toNumber: "123", message: "Hi Deep "} ] // create the lookup from the first array var lookup = a.reduce( function (lookUpObj, entryA) { // set the object property with the toNumber property lookUpObj[entryA.toNumber] = entryA.message return lookUpObj }, {}) // Now loop over the array and look for the differences var diff = b.reduce(function (arr, entryB) { // grab the entry from the lookup object we created var orginalMessage = lookup[entryB.toNumber] // if we do not have it listed OR the message is different // add it to the list as changed. if (.orginalMessage || orginalMessage.== entryB,message) { arr.push(entryB) } return arr }, []) console.log(diff)

Now that will match any differences from a to b.现在这将匹配从 a 到 b 的任何差异。 If anything was removed in B that is not in A it will not be caught.如果在 B 中删除了不在 A 中的任何内容,则不会被捕获。

Where is the problem???问题出在哪里???

 const a = [ { toNumber: "123", message: "Hi Deep " }, { toNumber: "321", message: "Test1" } ] const b = [ { toNumber: "321", message: "Test2" }, { toNumber: "123", message: "Hi Deep " } ] const diff = b.filter(eB=>.a.some(eA=>( eA.toNumber===eB.toNumber && eA.message===eB.message ))) document.write( JSON.stringify( diff ) )

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

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