Isaac Levin
Isaac Levin

Reputation: 1

Loop through array an insert values into it javascript

I have populated an array with databack from a webservice and need to populate the UI based on the last 6 years, even if they do not exist in the data. The Data coming back can be in terms of the UI incomplete, so what I need to do is insert values into the array for the "missing pieces".

Example

Data returns {2010, 2007}

What my javascript code must do is loop through the data returned, check the values of the indices, and insert values where needed.

UI returns (2010, 2009, 2008, 2007, 2006, 2005}

Also in 3 years when the dates have changed (current year is 2013)

Data returns {2011, 2009, 2008} UI returns {2013, 2012, 2011, 2010, 2009, 2008}


The array is populated with a return from a webservice, the webservice only puts values into the array that exist in the database, but the UI needs to display all values from the range 2010-2006 (ie data from the last 6 years, so in the future it could be 2015-2011)

Upvotes: 0

Views: 2121

Answers (2)

Ryan Kinal
Ryan Kinal

Reputation: 17732

If I understand correctly, you want to display the last 6 years, filling in data for whatever years you have data for. Easy enough:

var now = new Date(),
    year = now.getFullYear(),
    minYear = year - 6,
    data = getFromWebService(),
    thisData,
    i = 0,
    obj = {};

for (; i < data.length; i++)
{
    obj[data[i].year] = data[i];  // This effectively creates a year-indexed "array" of your objects
}

for (; year > minyear; year--)
{
    if (obj[year])
    {
        // There is data with the index 'year'
        // Do stuff with the data
    }
    else
    {
        // There is no data with the index 'year'
        // show the default UI
    }
}

This gets the current year, loops backward until it reaches 6 years previous, and tests to see if you have data for each of those years. You will need to fill in your own UI/data manipulation code, but this is the basic structure you'll need.

Upvotes: 1

djna
djna

Reputation: 55907

You need to define your rules. For example, what will you do in the case (2020, 2006)? Now you can't just get 6 items by filling in the gaps. Another example, what was the rule that leads you to add 2010 rather than 2005 to your example?

What would you do for input like (2005, 2008, 2006)? Is that order important?

Once you can clearly state the rules then the algorithm might fall ou, for example.

1). Sort in descending order - my example (2008, 2006, 2005)

2). Count how many extra values needed - 3 in my case.

3). Start at lowest value, look for gaps. Fill in the gaps until you have added the missing items.If any missing items left over add them at the start.

(2010, 2009, 2008, 2007, 2006, 2005)

implementing that in Javascript (or any such language) would be pretty trivial.

Upvotes: 0

Related Questions