Search code examples
javascriptarraysecmascript-6array-filterarray-map

ES6 array filter to remove common items


I am trying to remove common occurrence of slot_id in two arrays and to build an array of objects with no duplicates of slot_id.

Tried the following but its results an output array inside another array i.e. output [Array(0), Array(2)]. I am expecting an output array as follows.

Expected result:

[{
  "_id": "5b55c44038a7701a93fb1a68",
  "end_time": {
    "hours": "01"
  },
  "start_time": {
    "hours": "00"
  }
}, {
  "_id": "5b55c44038a7701a93fb1a67",
  "end_time": {
    "hours": "03"
  },
  "start_time": {
    "hours": "01"
  }
}]

Input arrays

Slots = [{
  "_id": "5b55c43532996fec4f500aa5",
  "time_slots": [{
    "_id": "5b55c43538a7701a93fb1a58",
    "end_time": {
      "hours": "01"
    },
    "start_time": {
      "hours": "00"
    }
  }, {
    "_id": "5b55c43538a7701a93fb1a57",
    "end_time": {
      "hours": "03"
    },
    "start_time": {
      "hours": "01"
    }
  }]
}, {
  "_id": "5b55c44032996fec4f500abf",
  "time_slots": [{
    "_id": "5b55c44038a7701a93fb1a68",
    "end_time": {
      "hours": "01"
    },
    "start_time": {
      "hours": "00"
    }
  }, {
    "_id": "5b55c44038a7701a93fb1a67",
    "end_time": {
      "hours": "03"
    },
    "start_time": {
      "hours": "01"
    }
  }]
}]

filterData = [{
  "slot_id": "5b55c43538a7701a93fb1a57",
  "user_id": "5b4dbbf9788bbb4fd01cea33"
}, {
  "slot_id": "5b55c43538a7701a93fb1a58",
  "user_id": "5b4dbbf9788bbb4fd01cea33"
}]

let result = Slots.map(m => m.time_slots.filter(e => !filterData.find(a => e._id == a.slot_id)));

Solution

  • use Array.prototype.reduce() concat array

    const Slots = [{"_id":"5b55c43532996fec4f500aa5","time_slots":[{"_id":"5b55c43538a7701a93fb1a58","end_time":{"hours":"01"},"start_time":{"hours":"00"}},{"_id":"5b55c43538a7701a93fb1a57","end_time":{"hours":"03"},"start_time":{"hours":"01"}}]},{"_id":"5b55c44032996fec4f500abf","time_slots":[{"_id":"5b55c44038a7701a93fb1a68","end_time":{"hours":"01"},"start_time":{"hours":"00"}},{"_id":"5b55c44038a7701a93fb1a67","end_time":{"hours":"03"},"start_time":{"hours":"01"}}]}];
    
    const filterData = [{"slot_id":"5b55c43538a7701a93fb1a57","user_id":"5b4dbbf9788bbb4fd01cea33"},{"slot_id":"5b55c43538a7701a93fb1a58","user_id":"5b4dbbf9788bbb4fd01cea33"}];
    
    const result = Slots.map(m => m.time_slots.filter(e => !filterData.find(a => e._id == a.slot_id))).reduce((accumulator, currentValue) => accumulator.concat(currentValue));
    
    document.write('<pre>' + JSON.stringify(result, null, '\t') + '</pre>')