Im making a function which compares two arrays of objects and returns two subset arrays of objects. The first returned array being a set of objects which were not included within the array passed within the second prop, and the second returned array being a set of objects which were not included within the first array but are now included within the second.
This works, however, i want to add an extra functionality to return the second array with specific keys. Is there anyway to utilise lodash "pickBy" functionality within the filter function, or will i have to create an extra recursive section?
function extract_removed_new (before, after, matching, pickBy = []) {
let before_ = cloneDeep(before)
let new_ = _.filter(after, (item) => {
let index_ = _.findIndex(before_, function (i) {
return _.get(i, matching) == _.get(item, matching)
})
if(index_ !== -1) {
before_.splice(index_, 1)
return false
}
if(pickBy.length > 0) {
return _.pickBy(item, function(value, key) {
if(key in pickBy) {
return true
}
});
}
return true
})
return [before_, new_]
}
Using lodash compact, with map I was able to get exactly what I needed.
function extract_removed_new (before, after, matching, pickBy = []) {
let before_ = cloneDeep(before)
let new_ = _.compact(_.map(after, (item) => {
let index_ = _.findIndex(before_, function (i) {
return _.get(i, matching) == _.get(item, matching)
})
if(index_ !== -1) {
before_.splice(index_, 1)
return false
}
if(pickBy.length > 0) {
return _.pickBy(item, function(value, key) {
if(pickBy.includes(key)) {
return true
}
});
}
return item
}))
return [before_, new_]
}