javascript中的数组差异

问题描述 投票:0回答:1

我知道这会很简单,但我试了两天,所以我终于决定向你们求助......我已经试过了。大概和我的问题一样 但它没有给我答案。

好了,这就是两个数组

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"}]

所以快速的帮助将是非常感激。

javascript jquery arrays multidimensional-array
1个回答
0
投票

所以,你的代码需要查看其他对象,看看它是否有任何匹配的键。如果它匹配,你需要看看消息是否匹配。所以你可以做一个有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)

如果在B中删除了A中没有的东西,就不会被发现。


0
投票

问题出在哪里?

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 ) )
© www.soinside.com 2019 - 2024. All rights reserved.