Given an array of target data…
1 2 3 4 5 |
var sortedWebcasts = [ { id: 136, providerName: "ATT", 'providerID': 36, 'active': true }, { id: 138, providerName: "Bell", 'providerID': 40, 'active': false }, { id: 140, providerName: "Verizon", 'providerID': 1, 'active': true } ]; |
We want to see if an array of ids can be found in that target data.
Say a user selects these ids:
1 2 3 4 |
var selectedIDs = [ { id : 136}, { id : 138} ] |
We want to see if the selected ids can be found in the target array:
1 2 3 4 |
// in array selectedIDs, for every {selectID}, // find if {selectID}.id matches for any element in array sortedWebcasts with id let idMatch = selectedIDs.map(selectID => _.find(sortedWebcasts, {id: selectID.id})) console.log(idMatch); |
Thus, you see that it looks through the target array on all the selected ids. If the ids match, then it saves it into an array and returns it to you:
output:
(2) [{…}, {…}]
0: {id: 136, providerName: “ATT”, providerID: 36, active: true}
1: {id: 138, providerName: “Bell”, providerID: 40, active: false}
length: 2
__proto__: Array(0)
You can also do it the other way, around, but it is not intuitive. You get every single target item and see if it exists in the toFind array.
It doesn’t fare very well as it forces you to go through every target item. If that target item is not found, undefined is returned and it sticks it into your result array. Thus, that is why we must use _.remove to removes those undefined. This is not the way to go.
1 2 |
let results = sortedWebcasts.map(webcast => _.find(selectedIDs, {id: webcast.id}) ) console.log(_.remove(results, undefined)) |