Ad
What Is The Best Way For Me To Retrieve This Information In A Sorted Manner?
Situation: I have a piece of code like
var DealsByMonth = {};
for (var region in this.DealsByRegion) {
this.DealsByRegion[region].forEach(function (deal) {
// deal.Created is in form like "2015-05-04T08:26:38Z"
var parts = deal.Created.split('-'),
monthstr = [parseInt(parts[1]), parseInt(parts[0])].join("/");
if (DealsByMonth[monthstr] !== undefined) {
++DealsByMonth[monthstr]
} else {
DealsByMonth[monthstr] = 0;
}
});
}
console.log(DealsByMonth); // TEST
var line_data = {
labels: [],
datasets: [
{
label: "MSfC Deals - Month by Month",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: []
}
]
};
for ( var key in DealsByMonth )
{
line_data.labels.push(key);
line_data.data.push(DealsByMonth[key]);
}
where what's being printed is an object like
{1/2015: 6, 2/2015: 14, 3/2015: 15, 4/2015: 24, 5/2015: 33, 6/2015: 16, 7/2015: 14, 8/2015: 22, 9/2015: 29, 10/2014: 41, 11/2014: 9, 11/2015: 14, 12/2014: 1, 12/2015: 32}
What I need to extract from that object is the keys but I need to go through them in order because I'm using them to draw a line graph. Either I need to go through them in order or I need to redo my code so that they're in a data structure that is already in order.
What is the correct way to approach this, in terms of elegance, efficiency, readability, etc.?
Ad
Answer
Off the top of my head, sort the keys, then use the sorted order
Object.keys(DealsByMonth).sort(function(a, b) {
var sa = a.split('/'); // index 0 = month, 1 = year
var sb = b.split('/');
var index = (sa[1] == sb[1]) ? 0 : 1; // if year is same, compare months
return parseFloat(sa[index]) - parseFloat(sb[index]);
}).forEach(function(key) {
line_data.labels.push(key);
line_data.data.push(DealsByMonth[key]);
});
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad