简体   繁体   中英

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. 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. 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. If anything was removed in B that is not in A it will not be caught.

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 ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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