简体   繁体   中英

underscore.js filter function using context

I am having trouble understanding how the _.filter() function works in undescorejs. Specifically, I am trying to understand if there is a way to return the values from the object being filtered, rather than the indices.

Assume the following:

var A = [1,2,3,4,5,8,10,12,15,20,25,30];

Now with a standard implementation:

_.filter(A, function(x) { return x % 5 == 0 ;})

This would return [5,10,15,20,25,30]. My problem arises with the following:

_.filter([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ;}, A)

This returns [4,6] which are the indices of the true values (those divisible by 5). But I would like to return the values of the true indices from the original array, that being [5,10].

From my understanding of other underscore.js function such as _.each() and _.map() this is how I would call the function using context.

_.map([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ; }, A)

Which would return [false,false,false,false,true,false,true]. I understand the _.filter() is calling _.each() internally to work through the array. So it makes sense that my call of _.filter([0,1,2,3,4,5,6], function(x) { return this[x] % 5 == 0 ;}, A) doesn't work, as the _.each() call is not receiving that this[x] value in its function.

Am I just missing something or is there just no way to call _.filter() that will return the values?

Somethisng like this?:

var indexes = [0,1,2,3,4,5,6];
_.filter(A, function(x, i) {
    return x % 5 == 0 && indexes.indexOf(i) > -1;
});

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM