Skip to content
Advertisement

Compare two Arrays and Insert Null Vallues

I have two arrays:

var array1 = [{id: 1, time: 100}, {id: 2, time: 200}, {id: 3, time: 300}];
var array2 = [{id: 1, time: 100}, {id: 3, time: 300}];

And I would like for array2 to be changed to

var array2 = [{id: 1, time: 100}, null, {id: 3, time: 300}];

The question is how can I compare the two arrays and look at their time and then insert null in the missing locations for each array.

Any help is appreciated!

Advertisement

Answer

Your example is a little misleading. Your description of the prompt says entries can be missing in both arrays, right? My example has 200 missing in array2, and 400 missing in array1

var array1 = [{ id: 1, time: 100 }, { id: 2, time: 200 }, { id: 3, time: 300 }];
var array2 = [{ id: 1, time: 100 }, { id: 3, time: 300 }, { id: 1, time: 400 }];
// get all possible times, sort them
const allSortedTimes = array1.map(({ time }) => time).concat(array2.map(({ time }) => time)).sort((a, b) => a - b)
// only use uniq times
const allUniqTimes = [...new Set(allSortedTimes)]
// now that we have all the possible times,
// we go over each array and check to see if that time exists
const insertedArray1 = allUniqTimes.map((uniqTime) => {
  return array1.find(({ time }) => time === uniqTime) ?? null
})

const insertedArray2 = allUniqTimes.map((uniqTime) => {
  return array2.find(({time}) => time === uniqTime) ?? null
})
console.log(insertedArray1)
console.log(insertedArray2)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement