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];
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);
but this only outputs [5] instead of [5, 10]
CodePudding user response:
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]
CodePudding user response:
This answer attempts to explicitly handle edge case/s (namely a number lower than the lowest page-size, ie: less than 5
). It returns a string "no pages"
but could be tailored to return something more appropriate as per the context.
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.