我正在尋找一種基于值減少/過濾陣列的方法。例如:
我有一個陣列:_postInsightSizeOptions: number[] = [5, 10, 25, 50, 100];
例如:
Input = 6 - the new array (_postInsightSizeOptionsFiltered) should only output [5, 10]
Input = 5 - the new array (_postInsightSizeOptionsFiltered) should only output [5]
Input = 28 - the new array (_postInsightSizeOptionsFiltered) should only output [5, 10, 25, 50]
我的嘗試:this._postInsightSizeOptionsFiltered = this._postInsightSizeOptions.filter(size => size <= 7);但這僅輸出 [5] 而不是 [5, 10]
uj5u.com熱心網友回復:
如果想要的值不存在,您可以取所有較小的值和下一個較大的值。
const
filter = (array, value) => array.filter((v, i, a) => v <= value || a[i - 1] < value),
data = [5, 10, 25, 50, 100];
console.log(...filter(data, 6)); // [5, 10]
console.log(...filter(data, 5)); // [5]
console.log(...filter(data, 28)); // [5, 10, 25, 50]
uj5u.com熱心網友回復:
這個答案試圖顯式處理邊緣情況(即小于最小頁面大小的數字,即:小于5)。它回傳一個字串"no pages",但可以根據背景關系進行定制以回傳更合適的內容。
代碼片段
const customFilter = (arr, num) => (
num < arr[0] ? ['no pages'] :
arr.filter((pgSz, idx) => {
if (pgSz <= num) return true; // if array-elt less than or equals "num"
if (idx > 0) { // for 2nd & subsequent array-elements
// if prev array-elt was less than "num"
// AND current array-elt greater than "num"
if (arr[idx-1] < num && num < pgSz) return true;
};
})
);
const data = [5, 10, 25, 50, 100];
console.log('case 1: ', ...customFilter(data, 6)); // [5, 10]
console.log('case 2: ', ...customFilter(data, 5)); // [5]
console.log('case 3: ', ...customFilter(data, 28)); // [5, 10, 25, 50]
console.log('case 4: ', ...customFilter(data, 4)); // [?]
console.log('case 5: ', ...customFilter(data, 105)); // [?]
解釋
在上面的代碼段中添加了行內注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/465566.html
標籤:javascript 数组 打字稿
