0

I have an array of messages like

oldMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} ]

and another array as

newMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} , {id:3,message:'message_C'} ]

How do I get only the part {id:3,message:'message_c'} by comparing oldMessages with newMessages? I must compare them based on their id only.

4
  • 1
    Hi and welcome. Can you post some code of what have you tried, please? Commented Jun 2, 2020 at 15:25
  • 1
    I wanted to, but my code is messed up, so I posted above example, any help on it is very much appreciated, thank you Commented Jun 2, 2020 at 15:29
  • 1
    And what have you investigated about it ??? Commented Jun 2, 2020 at 15:34
  • 1
    a few things about includes and filter in js Commented Jun 2, 2020 at 15:44

1 Answer 1

1

You can easily do this using array .find() method like:

const oldMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} ]
const newMessages = [ {id:1,message:'message_A'},{id:2,message:'message_B'} , {id:3,message:'message_C'} ]
const data = newMessages.find(r=> !oldMessages.map(x=>x.id).includes(r.id))

console.log( data )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.