On Sun, Mar 3, 2013 at 3:34 PM, Bjoern Hoehrmann <[email protected]> wrote:
> * David Bruant wrote:
> >I've found myself multiple times in a situation where I needed the index
> >of the first element responding to some conditions. I solved it the
> >following way:
> >
> > var index;
> > array.some(function(e, i){
> > if(someCondition(e)){
> > index = i;
> > return false;
> > }
> >
> > return true;
> > })
>
> It's usually a bad idea to trigger side-effects from such callbacks. The
> proper solution here would be having a suitable method available, like
>
> var index = array.findIndex(someCondition);
>
> as it is called in Haskell and C#.
>
This can be easily accomplished with Array.prototype.reduce:
function evaluate(str) {
return str === "b";
}
var array = [ "a", "b", "c" ];
var index = array.reduce(function(idx, val, i) {
return (idx === -1 && evaluate(val) && i ) || idx;
}, -1);
console.log( index ); // 1
But this won't stop the iteration, of course.
Rick
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss