In my JavaScript loop, I am iterating through notes stored in a database and combining them into a string to be added to the DOM. The noteType
serves as the key to categorize notes onto different tabs.
The challenge arises when I need to display a unified view of all notes sorted by date. At the conclusion of the loop, I concatenate the notes into a separate variable named combinedOutput
. While each note type is correctly ordered by date, merging them results in two orderly arrays getting appended according to their order, disrupting the chronological sequence in the final output.
Below is an excerpt of the code:
// Variables declared
var output = [],
combinedOutput = [],
noteType = '',
noteDate = new Date;
$(data).find('notes>data').each(function() {
var $p = $(this);
noteType = $p.find('noteType').text(),
noteDate = moment.utc($p.find('timestampOrig').text()).toDate()
if (typeof(output[noteType]) == 'undefined') {
output[noteType] = "";
}
if (typeof(combinedOutput[noteDate]) == 'undefined') {
combinedOutput[noteDate] = new Date;
}
// Constructing the note
output[noteType] += '<div id="message_' + $p.find('recordID').text() + '" class="panel panel-default custom-panel item">';
output[noteType] += 'Something Here';
output[noteType] += '</div>';
// Adding to the final output variable
combinedOutput[noteDate] += output[noteType];
});
Dates Example
**Note Type: Public**
April 1, 2017
March 5, 2017
April 8, 2017
**Note Type: Private**
April 2, 2017
March 9, 2017
March 11, 2017
**Combined Notes:**
April 1, 2017
March 5, 2017
April 8, 2017
April 2, 2017
March 9, 2017
March 11, 2017
The ultimate aim is to sort the combinedOutput
based on its key, which is a date object.
This screenshot displays the current unsorted state of the combinedOutput
array.
Link