0

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]

3
  • Why does output for 28 contains 50 ? Commented Apr 27, 2022 at 10:34
  • 10 is not <= 7. Why do you expect 10 to be in the output? Commented Apr 27, 2022 at 10:35
  • What is the logic? Why should 6 produce [5, 10] but 5 doesn't? Why does 28 also produce 50? Commented Apr 27, 2022 at 10:37

2 Answers 2

2

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]

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.