0

I am applying between condition in filtering of array based on another array. The example below works if array length is 1. If I have more than one, let's say var expText = ['1-3', '6-9']. In that case I want (Value >= lowerValue1 && Value < upperValue1) || (Value >= lowerValue2 && Value < upperValue2)

var Annual = [{"Date":1998,"Value":6.5},{"Date":1999,"Value":4},{"Date":2000,"Value":1},{"Date":2001,"Value":3}]
var expText = ['1-3']

expText2 = expText[0].match(/\d+/g);
lowerValue = parseInt(expText2[0]);
upperValue = parseInt(expText2[1]);

result = Annual.filter(function(v) { return (v.Value >= lowerValue && v.Value < upperValue) })

console.log(result);

1 Answer 1

2

In your filter(), just loop over your expText with some() and compare it to each one (meaning move your splitting bit into the loop as well). some() will return true if at least one of them match.

Or, to be technical, it will continue until one of them matches, at which point it'll return true it runs out of them to check and returns false.

const Annual = [{"Date":1998,"Value":6.5},{"Date":1999,"Value":4},{"Date":2000,"Value":1},{"Date":2001,"Value":3}];
const expTexts = ['1-3', '6-9'];

const result = Annual.filter(function(v) { 
  return expTexts.some(expText => {
    const expText2 = expText.match(/\d+/g);
    const lowerValue = parseInt(expText2[0]);
    const upperValue = parseInt(expText2[1]);

    return (v.Value >= lowerValue && v.Value < upperValue);
  });
});

console.log(result);

Side note: Obligatory "never, ever, ever use var, always use const or let".

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

5 Comments

You can seriously simplify the upper/lower parsing using split() and destructuring const [lowerValue, upperValue] = expText.split('-');
Completely agree. I just didn't because it wasn't part of the original question, but I'd definitely do the same in my code. Or even just destructing on the return of match() even.
That's fair enough
@samanime Thanks a ton. I am new to JS. can you a bit explain "never, ever, ever use var, always use const or let"?
TL;DR, var gets hoisted which causes it to end up in a weird scope that causes odd and hard-to-debug bugs. let and const act how most people would expect (don't get hoisted) and are less error-prone. Use const for values that don't change, let for values that do. Favor const and only switch to let when needed. This article seems to be a good longer explanation: medium.com/@codingsam/…

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.