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]
>Solution :
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]