Reputation: 1275
So I am looking for a function like Array.prototype.findIndex which returns an array of indexes. Like Array.prototype.find
and Array.prototype.filter
return one item and an array of items respectively. I was looking at MDN but couldn't find anything suitable.
I would like to stay compatible with future versions of javascript, is there something planned to be added?
Upvotes: 0
Views: 1181
Reputation: 3409
You can even use .map
var array1 = ['a', 'b', 'a'];
let data = array1.map((data,index) => data == "a" ? index : []).join('').split('')
console.log(data)
You can even just return the index by doing a forEach
and return the index if the callback matches.
Array.prototype.filterIndex = function(cb) {
let arr = [];
this.forEach((a, index) => {
if (cb(a)) arr.push(index)
})
return arr
}
var array1 = ['a', 'b', 'a'];
let data = array1.filterIndex((data) => data == "a")
console.log(data)
Upvotes: 0
Reputation: 3122
Why not use existing method Array.prototype.reduce
let out = ['a','b','a'].reduce((acc, curr, i) => (curr === 'a' && acc.push(i), acc), []);
console.log(out)
Upvotes: 1
Reputation: 665130
I guess the most suitable builtin method would be flatMap
which you can use for maybe-mapping an array:
['a', 'c', 'a', 'b'].flatMap((v, i) => v == 'a' ? [i] : [])
I am not aware of any proposal to add such a functionality. If you need this more often, you can write your own helper function:
function findIndices(array, callback, ctx) {
const res = [];
for (let i=0; i<array.length; i++)
if (callback.call(ctx, array[i], i, array))
res.push(i);
return res;
}
findIndices(['a', 'c', 'a', 'b'], v => v == 'a')
Upvotes: 1
Reputation: 386746
You could map the indices along with the value and get a callback and return an array of indices.
Array.prototype.filterIndex = function (cb) {
return this
.map((o, i) => [o, i])
.filter(([o]) => cb(o))
.map(([, i]) => i);
};
console.log(['a', 'b', 'a'].filterIndex(v => v === 'a'));
Upvotes: 1