Search code examples
javascripttypescriptlodash

Lodash retrieve index of the items from array of objects that have a boolean property equal to true


I am a beginner with lodash i went from c# and i have used LINQ sometimes, i have learned that lodash can be used to do query linq style, but despite my attempts, cant able to get index of the items, from array of objects that have a boolean property equal to true in lodash. Can anyone help me?

My first try :

var indexofItemns =_.find( arrayOfItems, (item) => 
  (item.booleanProperty === true));

But, I have an array and i do:

var indexItems: number[] = [];
indexItems= _.times(
  arrayOfItems.length,
  _.find( arrayOfItems, (item) => (item.booleanProperty === true)); 

the second row does not compile neither.

Thanks


Solution

  • You can achieve the same goal with pure JS. You don't need lodash

    const data = [{
        booleanProperty: false
      },
      {
        booleanProperty: true
      },
      {
        booleanProperty: false
      },
      {
        booleanProperty: true
      },
      {
        booleanProperty: false
      }
    ];
    
    const indexItems = data.map((item, index) => item.booleanProperty === true ? index : null).filter((item) => item !== null);
    
    
    console.log(indexItems)