Lodash, find indexes of all matching elements Lodash, find indexes of all matching elements typescript typescript

Lodash, find indexes of all matching elements


Here is a short solution:

Indexes = _.keys(_.pickBy(Animals, {Id: 3}))

output:

Indexes = ["3", "4"]

Use pickBy to pick element, and keys to get indexes.

pickBy is for object

_.pickBy(object, [predicate=_.identity])

Creates an object composed of the object properties predicate returns truthy for. The predicate is invoked with two arguments: (value, key).

https://lodash.com/docs/4.17.10#pickBy

But when use on array, it return a object like

{  3: {Name: "Horse", Id: 3},  4: {Name: "Pig", Id: 3}}

use _.keys on this object to get all keys in string array

["3", "4"]

If you want to get number array, use _.map

_.map(_.keys(_.pickBy(Animals, {Id:3})), Number)

You will get

[3, 4]


Another solution:

_.filter(_.range(animals.length), (i) => animals[i].id === 3);

id === 3 is the filter condition defined in the question above.


I think the most straight-forward way is to break it down: 1) we need to find out which objects have an ID of 3, 2) get rid of everything else, and 3) grab the indexes we're interested in.

_.chain(animals)    .map((animal, i)=> [i, animal.id === 3])    .filter(pair=> pair[1])    .map(pair=> pair[0])    .value();