I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range.
range = {
0: '25-500',
1: '1500-2500',
2: '5000-10000'
}
let price_values = [5, 100, 1500, 7000, 15000]
Here is my attempted solution
let nearestPriceRangeArr = [];
let rangeLength = Object.keys(range).length;
Object.keys(range).forEach(key => {
price_values.forEach((price, qKey) => {
let rangeArr = key.split("-");
let fromRange = parseInt(rangeArr[0]);
let toRange = parseInt(rangeArr[1]);
if(price <= fromRange) {
if(x == 0) {
nearestPriceRangeArr[price] = key;
}
} else {
if (price >= fromRange && price <= toRange) {
nearestPriceRangeArr[price] = key;
} else {
if(price >= toRange) {
let ab = (x == rangeLength - 1) ? key : key;
nearestPriceRangeArr[price] = ab;
}
}
}
x++;
});
});
Expected Result
nearestPriceRangeArr[5] = '25-500';
nearestPriceRangeArr[100] = '25-500';
nearestPriceRangeArr[1500] = '1500-2500';
nearestPriceRangeArr[7000] = '5000-10000';
nearestPriceRangeArr[15000] = '5000-10000';