How can i verify how many numbers in a array is in or out a 10-20 interval (10 and 20 included) in one function? I tried but i just got it with two functions, one to verify if its out and one to verify if its in.
let array = [1,3,7,10,14,18,20,23,27]
function inInterval(e){
if (e >= 10 && e <=20) {
return e
}
}
function outInterval(e) {
if (e <10 || e>20) {
return e
}
}
let inIntervalResult = array.filter(inInterval).length
let outIntervalResult = array.filter(outInterval).length
console.log(inIntervalResult, outIntervalResult)
CodePudding user response:
let array = [1,3,7,10,14,18,20,23,27]
let [outIntervalResult, inIntervalResult] =
array.reduce((r,e)=>(r[ (e >= 10 && e <=20)] , r), [0,0])
console.log(inIntervalResult, outIntervalResult)
Note that
coerces a true/false value to 1/0, and so concisely selects the index of the result to increment.
CodePudding user response:
You just need to find the number of elements in the range and minus this from total number of elements to get the number of elements out of the range.
Irrespective of the logic you use to count the number of elements for in or out of the range, you can return an object (or simply an array) with both counts inside.
var array = [1,3,7,10,14,18,20,23,27]
function countInOutRange(arr, min, max) {
let inRange = arr.filter(e => e >= min && e <= max).length
// Or use a simple for/forEach loop to count
let outRange = arr.length - inRange
return {inRange, outRange} // or [inRange, outRange]
}
console.log(countInOutRange(array, 10, 20))
CodePudding user response:
This should actually be fine!
You can also do
let outIntervalResult = e.length - inIntervalResult
If you don’t want to have two functions or filter twice.
CodePudding user response:
countall = (arr) => {
countin=0
countout=0
arr.forEach(x => (x<20 && x>10)?countin :countout )
return {'in':countin,'out':countout}
}
console.log(countall([1,3,5,7,12,15,17,11,20]))