-1

I have two arrays.

Array 1: One array is an array of objects:

arr1 = [{id:1, age:10}, {id:2, age:12}]

Array 2: The second array is just an array of ids:

arr2 = [3,4,1,5,2]

My goal is to combine the two arrays, but first taking the objects from the first array, and then to it joining the elements from the second array only taking the ids that are not already there in arr1. The second array elements need to be converted into objects. The end result of the above example will be:

newArray = [{id:1, age:10}, {id:2, age:12}, {id:3}, {id:4}, {id:5}]

I'm really confused about how to do this given the mix of objects and integers as array items.

asanas
  • 3,782
  • 11
  • 43
  • 72

2 Answers2

0

What you want to do is loop over arr2 and for each entry (integer) in that array, check if arr1 contains an object where the id property is equal to the entry in arr2 that you are handling. If that is not case, then you add (push) a new element to arr1 where the id property is set to the value of the element you handling from arr2.

You could do that with some javascript like this:

let arr1 = [{id:1, age:10}, {id:2, age:12}]
let arr2 = [3,4,1,5,2]

for (var i = 0; i < arr2.length; i++) {
  let id = arr2[i];
  if (!arr1.find(x => x.id === id)) {
    arr1.push({ id: id });
  }
}

console.log(arr1)
adiga
  • 34,372
  • 9
  • 61
  • 83
tmadsen
  • 941
  • 7
  • 14
-1

With reduce: You take as a base arr1, then run on every key in arr2, if the array dosn't have some object with same key, then add new object with new id.

const arr1 = [{ id: 1, age: 10 }, { id: 2, age: 12 }]
const arr2 = [3, 4, 1, 5, 2]

console.log(arr2.reduce((p,c) => (!p.some(x => x.id == c) && p.push({id:c}), p), arr1))
Ziv Ben-Or
  • 1,149
  • 6
  • 15