How to filter an array in Javascript by object value for the below example:
x = [1,2,3,4,5,6,7,8,9,10];
expected if I selected values
Start = 1;
End = 5;
Filtered array to be numbers between 1 to 5
newArray1 = [1,2,3,4,5];
and if I selected the below values
Start= 6;
End= 9;
Expected to get this values newArray2= [6,7,8,9];
NOTE: This need to be applied to use for clock hours and minutes to set schedule and durations and create booking slots.
comments inline
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // filter the arr based on start/end values const filter = (arr, start, end) => arr.filter((val) => val >= start && val <= end); console.log(filter(x, 1, 5)); console.log(filter(x, 6, 9)); // if results need be based on indexes const get = (arr, start, end) => arr.slice(start - 1, end); console.log(get(x, 1, 5)); console.log(get(x, 6, 9));
It's built into modern day JavaScript
x = [1,2,3,4,5,6,7,8,9,10];
function getRange(x, start, end) {
return x.filter(c=> c>= start&& c <= end)
}
console.log(getRange(x, 1, 5), getRange(x,6,9))
Assuming your array has only number values
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.