i have an array with couple of values like :
let myvar = 17
let myarray = [
{ start: 1, end: 10 },
{ start: 15, end: 22 },
{ start: 44, end: 47 }
]
I am looking for how to check if a variable is between the start and end of one of the objects in the array.
if myvar = 17, myfunction return true, because 17 is between 15 and 22 (the second object { start 15, end: 22 }), but if myvar = 12, myfunction return false.
CodePudding user response:
You can do it with some()
let data =
[
{ start: 1, end: 10 },
{ start: 15, end: 22 },
{ start: 44, end: 47 }
]
let num = 17
let result = data.some(d => d.start <=num && d.end >= num )
console.log(result)
Update: If you want to do it via function,then you can do it as below:
let myArray =
[
{ start: 1, end: 10 },
{ start: 15, end: 22 },
{ start: 44, end: 47 }
]
let myVar = 12
const myFunc = (num,data) => data.some(d => d.start <=num && d.end >= num)
console.log(myFunc(myVar,myArray))
CodePudding user response:
lucumt answer is not wrong but it didn't tell me which child of data is true. it just told me that it exists in there. so for that reason, I would use for each.
let data =
[
{ start: 1, end: 10 },
{ start: 15, end: 22 },
{ start: 44, end: 47 }
]
let num = 17
data.forEach(dc => {
// dc = data child
if (dc.start <= num && dc.end >= num) {
console.log(dc);
console.log(dc.start);
console.log(dc.end);
}
});