2
假設我們有如下所示的一系列產品,產品按名稱排序,然後按定價排序。 如何使用lodash獲得每個類別最便宜的產品或最昂貴的產品? 我們需要類似filterfirst
和filterlast
的功能。使用lodash的filterfirst和filterlast函數
[
{
"productId": "123456",
"name": "Daiper",
"category": "Home",
"store": "store1",
"pricing": 10
},
{
"productId": "123457",
"name": "Daiper",
"category": "Home",
"store": "store2",
"pricing": 20
},
{
"productId": "123458",
"name": "Daiper",
"category": "Home",
"store": "store3",
"pricing": 30
},
{
"productId": "123466",
"name": "Paint",
"category": "Home",
"store": "store2",
"pricing": 25
},
{
"productId": "123467",
"name": "Paint",
"category": "Home",
"store": "store1",
"pricing": 36
},
{
"productId": "123468",
"name": "Paint",
"category": "Home",
"store": "store3",
"pricing": 80
}
]
怎麼樣純JS解? –
'chain' - >'filter' - >'initial(offset)'或'chain' - >'filter' - >'slice(offset * -1)'會做你想做的。由於懶惰的評估,你不會得到整個鏈執行,但只是你想要的東西 - 所以,在第一個例子中,一旦到達「偏移」項,過濾將停止。第二個可能會被重寫爲與第一個相同,但帶有一個額外的'reverse','takeWhile'和'takeRightWhile'也可能是有趣的。 – vlaz