0

I have 2 arrays.

array1 = [1, 2, 3]
array2 = [{id:1}, {id:1}, {id:3}]

I want to get an array of objects with same id. Like when I go get all the object of 1 then I will loop through array2 and get the object then put them in a 3rd array.

I'm stuck at this point.

Update:

Thanks to flyingfox for solving my issue. But I see that if i have duplicate value in array1 the array2 doenst include it multiple time.

let array1 = [1, 3, 3, 3]
let array2 = [{id:1}, {id:2},{id:3}]

array1 = array1.filter(e1 => array2.some(e2 => e2.id === e1))
array2 = array2.filter(e1 => array1.some(e2 => e2 === e1.id))

here array2=[{id:1}, {id:3}]
But I want to get the duplicate as well. 
Like array2=[{id:1}, {id:3}, {id:3}, {id:3}] as array1 has 3 multiple time

1 Answer 1

1

If you just want to put all elements with same id into a new array,then below is a reference for you

let array1 = [1, 2, 3]
let array2 = [{id:1}, {id:1}, {id:3},{id:4}]

array1 = array1.filter(e1 => array2.some(e2 => e2.id === e1))
array2 = array2.filter(e1 => array1.some(e2 => e2 === e1.id))

let array3 = [...array1,...array2]
console.log(array3)

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

7 Comments

@ManasS.Roy Glad it can help you
what needs to be done to keep duplicate data inside array?
@ManasS.Roy Do not get what do you want,can you update your question or post a new question,please?
Thanks for your reply. I have updated the question. Please have a look
@ManasS.Roy can you post it into a new question,please?
|

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.