Home > Net >  Search higher in array
Search higher in array

Time:11-02

I have price combinations which are arrays of objects. And I have traveler ages which are an array of numbers. So price combinations have fields like min age and max age and I want to filter travelers ages higher or lower than min age or max age. am stuck on this really don't know how to do it.

  const travelerAges = [5, 10, 35, 50]

  priceCombinations.filter((priceCombination) => {
    if (priceCombination.minAge > travelerAges && priceCombination.maxAge > travelerAges) {
      return false
    } else if (priceCombination.maxAge < travelerAges) {
      return false
    }
    return true
  })

Getting error on IF.

Operator '>' cannot be applied to types 'number' and 'number[]'

Any ideas on how can I do this operation?

CodePudding user response:

I do not get the mentioned error while trying to execute your provided code. Yet one issue is that travelerAges is an array. You need to extract its lowest and highest value first.

Math.min(...travelerAges) //REM: Lowest value
Math.max(...travelerAges) //REM: Highest value

See Math.min and Math.max

//"traveler ages which are an array of numbers."
const travelerAges = [5, 10, 35, 50];

//"price combinations which are arrays of objects. price combinations have fields like min age and max age."
const priceCombinations = [];

//REM: Generating random data
for(let i=0; i<99; i  ){
    const
        tMax = Math.floor(Math.random() * 50),
        tMin = tMax - Math.floor(Math.random() * 50);

    priceCombinations.push({minAge: tMin, maxAge: tMax})
};

//"I want to filter travelers ages higher or lower than min age or max age."
//REM: Assuming that means to return all priceCombination with a minAge >= min and a maxAge <= max.
const filterPrices = (array, min, max) => {
    return array.filter((priceCombination) => {
        return (
            //REM: price has to be above or equal passed min
            priceCombination.minAge >= min &&
            //REM: price has to be below or equal passed max
            priceCombination.maxAge <= max
        )
    })
};

//REM: Calling the filter
console.log(
  'Min: '   Math.min(...travelerAges),
  'Max: '   Math.max(...travelerAges),
  
  filterPrices(
    priceCombinations,
    Math.min(...travelerAges),
    Math.max(...travelerAges)
  )
);

CodePudding user response:

choose array index first

for example:

travAgeMin = Math.min.apply(null, travelerAges)
travAgeMax = Math.max.apply(null, travelerAges)

priceCombinations.filter((priceCombination) => {
  if (priceCombination.minAge > travAgeMin && priceCombination.maxAge > travAgeMin) {
    return false
  } else if (priceCombination.maxAge < travAgeMax) {
    return false
  }
  return true
})
  • Related