Search code examples
javascriptlodash

Lodash Filter items by property value not in an array


I have an array of objects I am trying to filter using lodash. The end goal is to return any objects from the array where the value of a property is not in another array.

let inUse = ['1','2'];
let positionData = [{ 
    fieldID: '1',
    fieldName: 'Test1'
},
{ 
    fieldID: '2',
    fieldName: 'Test2'
},
{ 
    fieldID: '3',
    fieldName: 'Test3'
}]

// Only show me position data where the fieldID is not in our inUse array
const original = _.filter(positionData, item => item.fieldID.indexOf(inUse) === -1);

I tried using indexOf but I don't think I am using it right in this situation.

Expected Result:

original = { 
 fieldID: '3',
 fieldName: 'Test3'
}

Solution

  • It looks like you have your indexOf backwards; currently, it's looking for inUse inside of item.fieldID.

    Try this:

    const original = _.filter(positionData, item => inUse.indexOf(item.fieldID) === -1);