I have array of four JS object:
Object1 = {
fee: 150
}
Object2 = {
fee: 300
}
Object3 = {
fee: 450
}
Object4 = {
fee: 700
}
I need to find object where value that I provide via input is greater then fee of object but also less than fee of next one. There is also a case where value can not be less than fee of first one and if value is greater than fee of four one I need four one as result.
For example:
value = 50, result = null,
value = 225, result = Object1,
value = 400, result = Object2,
value = 650, result = Object3,
value = 1500, result = Object4,
You mean something like this?
let obs = [{fee: 150}, {fee: 300}, {fee: 450}, {fee: 700}];
function findObject(currentFee) {
// in case it is not garanteed that obs is sorted, doing this
// would be necessary beforehand
return obs.filter(o => o.fee > currentFee)[0]
};
Is this what you were looking for?
var objects = [{fee: 150}, {fee: 300}, {fee: 450}, {fee: 700}];
function find(input) {
for (let i = 0; i < objects.length; i++) {
if (objects[i + 1]) {
if (objects[i].fee < input && input < objects[i + 1].fee) return objects[i].fee;
}
}
return null;
}
console.log(find(701));
I used filter with index. My answer is similar to the good answer by @RomanHDev. But my approach was to immediately use the index to decrement the match.
const obs = [{fee: 150}, {fee: 300}, {fee: 450}, {fee: 700}];
findObject = feeParam => obs.filter((o, i) => {
if (o.fee >= feeParam) {
return obs[i] ?? null;
}
})[0]
console.log( findObject('25',25) )
console.log( findObject('155',155) )
console.log( findObject('225',225) )
console.log( findObject('301',301) )