2017-08-10 107 views
2

從Python和Numpy中,我發現自己經常使用的典型特徵是布爾型掩碼。Javascript中的布爾型數組掩碼

下面是在Python一個例子:

>>> mylist = np.array([50, 12, 100, -5, 73]) 
>>> mylist == 12 
array([False, True, False, False, False]) # A new array that is the result of .. 
              # .. comparing each element to 12 
>>> mylist > 0 
array([True, True, True, False, True])  # A new array that is the result of .. 
              # .. comparing each element to 0 
>>> mylist[mylist == 12] 
array([12])        # A new array of all values at indexes .. 
              # .. where the result of `mylist == 12` is True 

>>> mask = mylist != 100     # Save a mask 
>>> map(foo, mylist[mask])     # Apply `foo` where the mask is truthy 

通常,當np.array由相同尺寸的另一個數組索引,返回一個新的數組含有這些索引,其中所述掩模陣列的值是truthy的元素。

我可以在Javascript中使用Array.prototype.mapArray.prototype.filter做類似的事情,但它更冗長,我的面具被銷燬。

-> mylist = [50, 12, 100, -5, 73] 
-> mylist.map(item => item == 12) 
<- [false, true, false, false, false]  // mylist == 12 

-> mylist.filter(item => item == 12) 
<- [12]         // mylist[mylist == 12] 

-> mask = mylist.map(item => item == 12) 
-> mylist.filter(item => mask.unshift()) 
<- [12]         // mylist[mask] 

-> mask 
<- []          // Mask isn't reusable 

有沒有在JavaScript應用口罩在陣列的一個更好的辦法還是我卡住製作面具的副本,每次使用filtermap

+0

[* map *](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)創建一個新數組,它不會破壞原始數組。 – RobG

+0

'.unshift()'雖然 - 否則我需要一個索引掩碼條目。 –

+0

傳遞給* filter *的函數需要3個參數,值,索引和原始對象。所以有你的索引。或者編寫你自己的擴展,比如'Array.prototype.maskFilter',它只是索引。 – RobG

回答

1

Both filter and map創建新的數組,使他們很好。但是,您使用unshift似乎是因爲您想要索引而不是價值。你可以通過該指數在呼叫:

var mylist = [50, 12, 100, -5, 73]; 
 
var mask = mylist.map(item => item == 12); 
 
var newlist = mylist.filter((item, i) => mask[i]); 
 

 
console.log(newlist);

,或者如果你不希望傳遞一個以上的值,你可以寫你自己的maskFilter Array.prototype的方法只需一個面膜來代替:

Array.prototype.maskFilter = function(mask) { 
 
    return this.filter((item, i) => mask[i]); 
 
} 
 

 
var mylist = [50, 12, 100, -5, 73]; 
 
var mask = mylist.map(item => item == 12); 
 
var newlist = mylist.maskFilter(mask); 
 

 

 
console.log(newlist); // [12] 
 
console.log(mylist); // untouched