0

I have two arrays. I want to compare them and make a new array out of it with matched values but I want to keep duplicate values as well.

Like:

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

output:

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

But I want to get the duplicate as well.

Desired output

array2=[{id:1}, {id:3}, {id:3}, {id:3}] //as array1 has 3 multiple time
0

1 Answer 1

1

We can use Array.filter() and Array.map() to change data of array1,then assign it to array2

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

array2 = array1.filter(e1 => array2.some(e2 => e2.id === e1)).map(e => ({'id':e}))

console.log(array2)


Update:without assign value from array1 to array2

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

array1 = array1.reduce((a,v) =>{
  a[v] = a[v]??0
  a[v] += 1
  return a
},{})

array2 = array2.reduce((a,v) =>{
  let cnt = array1[v.id]
  for(let i=0;i<cnt;i++){
   a.push({...v})
  }
  return a
},[])  

console.log(array2)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.