Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - Filter List of Numbers Using a List of Ranges

I have a List of ages and a List of ageRanges, using javascript I am tying to filter the ages that fall within any of the ageRanges

I got code working for a single ageRange, but how can I do this if ageRanges is an array?

Example of code I used with a single ageRange:

 var ages = [32, 33, 16, 22, 40];

var ageRanges = {min: 10, max:23};

function checkAdult(age) {
  return age >= ageRanges.min && age <= ageRanges.max;
}

function myFunction() {
  document.getElementById("demo").innerHTML = ages.filter(checkAdult);
} //returns 16,22

Example of the data I want to filter:

var ages = [32, 33, 16, 22, 40];

var ageRanges = [{min: 10, max:23},{min:30, max:36},{min:44, max:49}];

I tried doing a for loop, but struggled to get it right as I'm definitely new to all this so any help would be appreciated. Also started to wonder if a for loop was even the riI can easily format the ageRanges data differently if there is a better way to represent a list of ranges

question from:https://stackoverflow.com/questions/65830385/filter-list-of-numbers-using-a-list-of-ranges

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, use Array.prototype.some() along with Array.prototype.filter():

const ages = [32, 33, 16, 22, 40],
      ageRanges = [{min: 10, max:23},{min:30, max:36},{min:44, max:49}],
      
      result = ages.filter(age => 
        ageRanges.some(({min,max}) => 
          age >= min && age <= max))
          
console.log(result)          

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...