简体   繁体   English

根据输入减少/过滤数组

[英]Reduce/Filter Array based on input

Im looking to find a way to reduce/filter an array based on a value.我正在寻找一种方法来根据值减少/过滤数组。 So for example:例如:

I have an array: _postInsightSizeOptions: number[] = [5, 10, 25, 50, 100];我有一个数组: _postInsightSizeOptions: number[] = [5, 10, 25, 50, 100];

For Example:例如:

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]

My Attempt: this._postInsightSizeOptionsFiltered = this._postInsightSizeOptions.filter(size => size <= 7);我的尝试: this._postInsightSizeOptionsFiltered = this._postInsightSizeOptions.filter(size => size <= 7); but this only outputs [5] instead of [5, 10]但这只输出 [5] 而不是 [5, 10]

You could take all smaller values and the next greater value if the wanted value does not exist.如果所需值不存在,您可以采用所有较小的值和下一个较大的值。

 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]

This answer attempts to explicitly handle edge case/s (namely a number lower than the lowest page-size, ie: less than 5 ).该答案试图明确处理边缘情况(即低于最低页面大小的数字,即:小于5 )。 It returns a string "no pages" but could be tailored to return something more appropriate as per the context.它返回一个字符串"no pages" ,但可以根据上下文进行调整以返回更合适的内容。

Code Snippet代码片段

 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)); // [?]

Explanation解释

Inline comments added in the snippet above.在上面的代码片段中添加了内联评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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