Find index of all matched records of array
Photo by Max Duzij on Unsplash
There are several ways to find an index of particular/multiple records of the array. In this article, I'll share an easy and efficient way to achieve it. ( Let me know what you do in comment 😋 )
Guess you have tons of records in an array and you want to get indexes of records which match with your condition, IndexOfAll() is a function to use in those cases. This snippet will take array and function as input and return an array of indexes of records that matched with given function/condition. Let me show how snippet works...
const indexOfAll = (arr, fn) => arr.reduce((acc, el, i) => (fn(el) ? [...acc, i] : acc ) , )
As you see, I'm getting array (as arr) and prediction function (as fn)& arguments as parameters of this function. And in return, I've trigged an array method called reduce ( this method executes a reducer function (that you provide) on each element of the array, resulting in single output value, read more )*.
Inside of reduce method, I've defined empty array in the second argument as an initial value and in the first argument, I've executed function (fn) with a current record where if it'll return positive value then concatenate it's an index into a resulting array(acc) by using spreading operator ( it's a concept of ES6 - check more in detail here. ) otherwise return array as it is.
Okay, How to use it? 🤔
const array = [1, 2, 3, 1, 2, 3] const result = indexOfAll(array, (x) => x === 1); // output :- [ 0, 3 ]
Simple as that, need to pass an array of records as first arguments and prediction function as second arguments. In the given example, if you see I've added condition that index of record with value "1" should include into resulting array and in output, we have a position of matched record from the
There must be some other ways too ( shares it in a comment if you have in mind 😀). But among all I found this one clean and neat for a solution so, I thought to share it with you too. ope this will help you, yes? then hit follow 😂.
Learn Something New Everyday,
Connect With The Best Developers!