1

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

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

You beat me to it, your answer is basically identical to mine so I've removed it
1

If you need a single index satisfying that condition, you can use findIndex of es6 or lodash

data.findIndex(a=>a.booleanProperty)

If you need all the indexes satisfying your condition, you can either map and filter together sequentially (as shown in ben's answer) or you can merge them to a single reduce to iterate only once and build your index array. here we go:

data.reduce((r, a, i)=> (a.booleanProperty && r.push(i), r), [])

let data = [{"booleanProperty":false},{"booleanProperty":true},{"booleanProperty":false},{"booleanProperty":true},{"booleanProperty":false}];
    
let indexes = data.reduce((r, a, i)=> (a.booleanProperty && r.push(i), r), []);
  
  
console.log(indexes);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.