1

This is driving me crazy.

I'm trying to do a get an array that is the difference between two arrays containing json objects.

I can do this easily with arrays of primitive values, by using sets. I mainly come from a Java background not JavaScript and this seems annoyingly difficult.

const available = [{time:1, chargable: true}, {time:2, chargable: false}, {time:3, chargable: true},{time:4, chargable: true}];
const booked = [{time:2, chargable: false}, {time:3, chargable: false}, {time:4, chargable: false}];

const remainingAvailable = findRemainingAvailable(available, booked)

I want remainingAvailable to contain: [{time:1, chargable: true}]

How do I do that (ideally using funky functions like filter etc)?

kaylanx
  • 908
  • 1
  • 8
  • 11
  • So even if the `chargable` state is different, as long as the `time` is the same it's considered the same? – Terry Apr 10 '20 at 20:48

2 Answers2

1

Based on your provided data and expected output, it seems like you do not care about the chargable state of the objects, but only want to compare them based on the value of time.

Then, all you need is to create a mapped array containing all the time values in the booked array, and then filter the available array of objects, only keeping entries whose time is not found in the mapped array:

const available = [{time:1, chargable: true}, {time:2, chargable: false}, {time:3, chargable: true},{time:4, chargable: true}];
const booked = [{time:2, chargable: false}, {time:3, chargable: false}, {time:4, chargable: false}];

function findRemainingAvailable(available, booked) {
  // Only compare based on time
  const bookedTimes = booked.map(x => x.time);

  return available.filter(({ time }) => !bookedTimes.includes(time));
}

const remainingAvailable = findRemainingAvailable(available, booked);
console.log(remainingAvailable);
Terry
  • 63,248
  • 15
  • 96
  • 118
1

You could take a set for booked times and filter the available times.

const
    findRemainingAvailable = (a, b) => {
        const booked = new Set(b.map(({ time }) => time))
        return a.filter(({ time }) => !booked.has(time))
    },
    available = [{ time: 1, chargable: true }, { time: 2, chargable: false }, { time: 3, chargable: true }, { time: 4, chargable: true }],
    booked = [{ time: 2, chargable: false }, { time: 3, chargable: false }, { time: 4, chargable: false }],
    remainingAvailable = findRemainingAvailable(available, booked);

console.log(remainingAvailable);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392