Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h1>How to fill in missing elements in an array describing a range</h1> <p>Presuming the starting array is already sorted, you might want to copy the first element in the source array into a new one and then iteratively push "default objects" into the destination array or copy from the source array when there is a matching object. Repeat until you reach the end of your range.</p> <p>To check if there is a matching object, you might want to index first the source array by whatever parameter you want to iterate over (in your case: the "joined" field). This means that this parameter has to be unique.</p> <pre><code>function getIndex(srcArray, field) { var i, l, index; index = []; for(i = 0, l = srcArray.length; i &lt; l; i++) { index[srcArray[i][field]] = srcArray[i]; } return index; } </code></pre> <p>This creates a hashmap of your array. Searching an element by it's key (in your case the "joined" field) is very simple: </p> <pre><code>if(index['2013-06-05'] !== undefined) { /* the element indexed by "2013-06-05" exists */ } </code></pre> <p>Now that you have an index, you can iterate over the range you expect to have. For this, get the first and the last dates in your source array:</p> <pre><code>//get boundaries var first = new Date(src[0].joined); var last = new Date(src[src.length-1].joined); </code></pre> <p>You also need to know how to construct your default objects:</p> <pre><code>function createDefault(datestr) { return {users: 0, joined: datestr}; } </code></pre> <p>Now declare a destination array and iterate over the range:</p> <pre><code>var dest = []; for(var d = first; d.getTime() &lt;= last.getTime(); d.setDate(d.getDate()+1)) { datestr = dateToYMD(d); //dateToYMD is a helper function I declared that formats a date if(index[datestr]) { //this date exists in your data, copy it dest.push(index[datestr]); } else { //this date does not exist, create a default dest.push(createDefault(datestr)); } } </code></pre> <p>I made a jsfiddle that logs the destination array to console. <a href="http://jsfiddle.net/uNasR/" rel="nofollow">http://jsfiddle.net/uNasR/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload