JS count numbers between

datasets: [
  { label: 'A', data: [82, 160, 10, 40, 179] },
  { label: 'B', data: [101, 180, 80, 85, 119] },
  { label: 'C', data: [124, 160, 99, 130, 43] },
  { label: 'D', data: [66, 153, 82, 81, 97] }
]

what is the best (shortest) way to make data like this:

datasets: [
  { label: 'A', data: [
    {'fits': '180', 'counter': 0},
    {'fits': '160+', 'counter': 2}, //160, 179
    {'fits': '140+', 'counter': 0},
    {'fits': '120+', 'counter': 0},
    {'fits': '100+', 'counter': 0},
    {'fits': '80+', 'counter': 1}, //82
    {'fits': '60+', 'counter': 0},
  ]},
  { label: 'B', data: [
    {'fits': '180', 'counter': 1}, //180
    {'fits': '160+', 'counter': 0},
    {'fits': '140+', 'counter': 0},
    {'fits': '120+', 'counter': 0},
    {'fits': '100+', 'counter': 2}, //101,119
    {'fits': '80+', 'counter': 2}, //80,85
    {'fits': '60+', 'counter': 0},
  ]},
  { label: 'C', data: [
    {'fits': '180', 'counter': 0},
    {'fits': '160+', 'counter': 1}, //160
    {'fits': '140+', 'counter': 0},
    {'fits': '120+', 'counter': 2}, //124, 130
    {'fits': '100+', 'counter': 0},
    {'fits': '80+', 'counter': 1}, //99
    {'fits': '60+', 'counter': 0},
  ]},
  { label: 'D', data: [
    {'fits': '180', 'counter': 0},
    {'fits': '160+', 'counter': 0},
    {'fits': '140+', 'counter': 1}, //153
    {'fits': '120+', 'counter': 0},
    {'fits': '100+', 'counter': 0},
    {'fits': '80+', 'counter': 3}, //82,81,97
    {'fits': '60+', 'counter': 1}, //66
  ]}
]

>Solution :

const datasets = [
    { label: 'A', data: [82, 160, 10, 40, 179] },
    { label: 'B', data: [101, 180, 80, 85, 119] },
    { label: 'C', data: [124, 160, 99, 130, 43] },
    { label: 'D', data: [66, 153, 82, 81, 97] },
];

const handleDatasets = (datasets) => {
    const fits = [180, 160, 140, 120, 100, 80, 60];

    return datasets.map((set) => {
        return {
            ...set,
            data: fits.map((num, i) => {
                return {
                    fits: num,
                    counter: set.data.filter((dataNum) => (dataNum >= num && (fits[i - 1] ? dataNum < fits[i - 1] : true))).length,
                };
            }),
        };
    });
};

console.log(handleDatasets(datasets));

Leave a Reply