javascript中的数组差异
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript中的数组差异相关的知识,希望对你有一定的参考价值。
我知道这会很简单,但我试了两天,所以我终于决定向你们求助......我已经试过了。大概和我的问题一样 但它没有给我答案。
好了,这就是两个数组
a = [{toNumber: "123", message: "Hi Deep "}, {toNumber: "321", message: "Test1"}]
b = [{toNumber: "321", message: "Test2"}, {toNumber: "123", message: "Hi Deep "}]
我想要的是
diff = [{toNumber: "321", message: "Test2"}]
所以快速的帮助将是非常感激。
答案
所以,你的代码需要查看其他对象,看看它是否有任何匹配的键。如果它匹配,你需要看看消息是否匹配。所以你可以做一个有id列表的查找对象。你可以在你的第二个数组中循环,看看它们是否匹配。
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)
另一答案
问题出在哪里?
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 ) )
以上是关于javascript中的数组差异的主要内容,如果未能解决你的问题,请参考以下文章