Array.filter: max number of matches?

Rick Waldron waldron.rick at gmail.com
Tue Nov 13 15:38:38 PST 2012


On Tue, Nov 13, 2012 at 3: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.


Definitely, but it works without the slice(), too:

var filtereds, items, limit, k;

items = new Array(1000).join("-").split("");
limit = 3;
k = 0;

filtereds = items.filter(function( val, i, orig ) {
  if ( true ) {
    if ( ++k === limit ) {
      orig.length = 0;
    }
    return true;
  }
});

console.log( filtereds );
// [ '-', '-', '-' ]


Rick



>
>
> /be
>
>
> ______________________________**_________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/**listinfo/es-discuss<https://mail.mozilla.org/listinfo/es-discuss>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121113/2a6d3987/attachment.html>


More information about the es-discuss mailing list