From 2a3c493de73fc812367bc3da5103cede4fe4c374 Mon Sep 17 00:00:00 2001 From: toridenney <51720657+toridenney@users.noreply.github.com> Date: Thu, 23 Jul 2020 09:25:30 -0500 Subject: [PATCH] Update to BarChart.js to resolve sorting issue --- src/BarChart.js | 50 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/src/BarChart.js b/src/BarChart.js index a6db85f..a7deaee 100644 --- a/src/BarChart.js +++ b/src/BarChart.js @@ -62,22 +62,40 @@ class BarChart extends React.Component { } }); } - - sortAxis = (i, descending) => { - if(descending === undefined) descending = true; - let toSort = Object.keys(this.props.data).map(name => { - return { - name: name, - val: this.props.data[name][i] - }; - }); - toSort.sort((left, right) => descending ? left.val < right.val : left.val > right.val); - toSort = toSort.slice(0, this.maxItems); - const maxVal = Math.max.apply(Math, toSort.map(item => item.val)); - return [toSort.reduce((ret, item, idx) => ({ - ...ret, ...{[item.name]: idx} - }), {}), maxVal]; + + /** + * sortAxis + * Handles sorting the results + * @param {*} i is the item to start sorting from + * @param {number} maxItems is the maximum number of items to allow in the list + * @param {*} descending is the direction to sort + */ + sortAxis = (i, descending) => { + if(descending === undefined) descending = true; + // Build a new array to sort e.x. { name: 'some name', val: 1 } + let toSort = Object.keys(this.props.data).map(name => { + return { + name, + val: this.props.data[name][i] + }; + }); + // Handle the sorting based on the values + toSort.sort((left, right) => left.val - right.val) + if (descending) { + toSort.reverse() + } + // Slice based on the maximum items allowed + const fItems = Object.keys(this.props.data).length + if (this.maxItems && this.maxItems <= fItems) { + toSort = toSort.slice(0, this.maxItems) } + const maxVal = Math.max.apply(Math, toSort.map(item => item.val)) + const minVal = Math.min.apply(Math, toSort.map(item => item.val)) + // Sorted list of results based on the axis + return [toSort.reduce((ret, item, idx) => ({ + ...ret, ...{ [item.name]: idx } + }), {}), minVal, maxVal] + } getInfoFromRank = name => { const currIdx = this.state.idx; @@ -131,4 +149,4 @@ class BarChart extends React.Component { } } -export default BarChart; \ No newline at end of file +export default BarChart;