如何在Javascript中按对象值筛选数组,例如:
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];
如果我选择了以下值
Start= 6;
End= 9;
应获取此值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.
注释内联
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));
它内置于现代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))
假设您的数组只有数值