Home > Enterprise >  Join array based on another array
Join array based on another array

Time:03-28

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

CodePudding user response:

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".

  • Related