Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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];

For Example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading