Array.filter: max number of matches?

Andrea Giammarchi andrea.giammarchi at gmail.com
Tue Nov 13 15:33:03 PST 2012


Alex, here is how you should use the Array#some in order to solve your
problem:

var howManyConditions = 5;
yourArray.some(function (value) {
  if (conditionSatisfied(value)) {
    --howManyConditions;
  }
  return !howManyConditions;
});

in this case, as Brendan said, you don't even need a copy.

If the creation of new variables is the problem ...

yourArray.some(function(value){
  if (conditionSatisfied(value)) {
    --this.breakLoop;
  }
  return !this.breakLoop;
}, {breakLoop:5});

you can reuse both callback, if defined elsewhere once, and the object for
those conditions ... well, you have many options, same is for every. One
thing you might need is to save the last index somehow if needed for a
splice later on.

br


On Tue, Nov 13, 2012 at 1:12 PM, Alex Vincent <ajvincent at gmail.com> wrote:

> The some method, as currently implemented, isn't truly better.
> Mathematically, I think Array.prototype.some would be equivalent to my
> suggested Array.prototype.filter(callback, thisObj, 1);
>
>
> On Tue, Nov 13, 2012 at 12:33 PM, Brendan Eich <brendan at mozilla.org>wrote:
>
>> Andrea Giammarchi wrote:
>>
>>> wait, I might have misunderstood your problem ... so you want to stop
>>> iterating, right ?
>>>
>>> When that is the case, you can simply drop the iteration like this:
>>>
>>> myArray.slice().filter(**function (value, index, original) {
>>>   // do your stuff
>>>   if (conditionSatisfied) {
>>>     original.length = 0;
>>>   }
>>> });
>>>
>>> there, you can break the iteration as easy as that :-)
>>>
>>
>> Making a copy and then mutating its length seems worse than using some,
>> though.
>>
>> /be
>>
>>
>
>
> --
> "The first step in confirming there is a bug in someone else's work is
> confirming there are no bugs in your own."
> -- Alexander J. Vincent, June 30, 2001
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121113/93eee24a/attachment.html>


More information about the es-discuss mailing list