'Filtering range of values from json object
I'm stuck at filtering a range of values from a json object.
Below is the Range data
const contractAmountRange = [
{ id: '1', min: 0, max: 100000, description: 'Less than $100,000' },
{
id: '2',
min: 100001,
max: 500000,
description: '$100,001 to $500,000',
},
{
id: '3',
min: 500000,
max: 1000000,
description: '$500,000 to $1,000,000',
},
{
id: '4',
min: 1000001,
max: 5000000,
description: '$1,000,001 to $5,000,000',
},
{
id: '5',
min: 5000000,
description: 'More than $5,000,000',
},
];
If any one of the range is selected, i need to filter json object with that chosen range. the structure of the json object are as followed:
const data = [
{
tenderNo: 'ASHQ17HH26334',
awardedAmt: 400000,
yearAwarded: 2015,
},
{
tenderNo: 'BFG8765TT14000008',
awardedAmt: 300000,
yearAwarded: 2015,
},
{
tenderNo: 'AFSH00ETT14000009',
awardedAmt: 76071.21,
yearAwarded: 2015,
},
];
This is where I'm at right now.
data is json object
contractAmountRange is the array of available range
rangeSelected is the chosen range, it is represented by its id
const filterData = (data,contractAmountRange,rangeSelected) => {
// let maxRange, minRange;
const rangeMap = {};
for (const item of contractAmountRange) {
rangeMap[item.id] = item;
}
const filteredData = data.filter((el) => {
return (
?????
);
Solution 1:[1]
First find the selected range, then filter the elements whose awardedAmt is included between found min and max:
const contractAmountRange = [{
id: "1",
min: 0,
max: 100000,
description: "Less than $100,000"
},
{
id: "2",
min: 100001,
max: 500000,
description: "$100,001 to $500,000",
},
{
id: "3",
min: 500000,
max: 1000000,
description: "$500,000 to $1,000,000",
},
{
id: "4",
min: 1000001,
max: 5000000,
description: "$1,000,001 to $5,000,000",
},
{
id: "5",
min: 5000000,
description: "More than $5,000,000",
},
];
const data = [{
tenderNo: "ASHQ17HH26334",
awardedAmt: 400000,
yearAwarded: 2015,
},
{
tenderNo: "BFG8765TT14000008",
awardedAmt: 300000,
yearAwarded: 2015,
},
{
tenderNo: "AFSH00ETT14000009",
awardedAmt: 76071.21,
yearAwarded: 2015,
},
];
const filterData = (data, contractAmountRange, rangeSelected) => {
const foundRange = contractAmountRange.find((x) => x.id === rangeSelected);
if (!foundRange) {
throw new Error("No range found!");
}
const {
min,
max
} = foundRange;
return data.filter(
({
awardedAmt
}) => awardedAmt >= min && awardedAmt <= max
);
};
const output = filterData(data, contractAmountRange, "2");
console.log(output);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | moonwave99 |
