Slim down Javascript MomentJS Function I have a drop down menu that will run a function onchange. The function takes times from an array , adds a specific amount of time , then changes the innerHTML of the table.

The code works , but is there a simpler version? I plan on adding more options to the drop down menu.

HTML

&lt;select id="sel1" onchange="myFunction()"&gt;

   &lt;option value="VIC"&gt;VIC&lt;/option&gt;
   &lt;option value="NSW"&gt;NSW&lt;/option&gt;

&lt;/select&gt;

&lt;table id="myTable" border="1"&gt;
&lt;tbody&gt;
    &lt;tr&gt;
        &lt;td&gt;A&lt;/td&gt;
        &lt;td&gt;2016-08-24 16:00&lt;/td&gt;
        &lt;td&gt;C&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
        &lt;td&gt;A&lt;/td&gt;
        &lt;td&gt;2016-08-24 16:00&lt;/td&gt;
        &lt;td&gt;C&lt;/td&gt;
    &lt;/tr&gt;
&lt;/tbody&gt;


Javascript

function myFunction(){

var cellData = ["2016-08-24 15:45", "2016-08-24 16:00"];
var myTable = document.getElementById("myTable");

if (document.getElementById("sel1").value == "VIC") {

var vicTime = [];

for (i=0; i&lt;cellData.length; i++) {

date = moment(cellData[i]).add(1, 'h').format('MM/DD/YYYY hh:mm a');

vicTime.push(date);

myTable.rows[i].cells[1].innerHTML = vicTime[i];

}}

if (document.getElementById("sel1").value == "NSW") {

var nswTime = [];
var j;

for (j=0; j&lt;cellData.length; j++) {

date = moment(cellData[j]).add(5, 'h').format('MM/DD/YYYY hh:mm a');

nswTime.push(date);

myTable.rows[j].cells[1].innerHTML = nswTime[j];

}}};
When you find yourself repeating code like this (just with slight differences), that's usually a sign that it's time to separate the logic into its own function so it can be reused. You could also maybe clean up your conditionals using a switch statement too - but that's more of a personal taste thing.

Here's my take on it:

function myFunction() {
    var cellData = ["2016-08-24 15:45", "2016-08-24 16:00"];
    var myTable = document.getElementById("myTable");

    // Defined inside the function so the data/table are in scope -
    // alternatively, you could define it outside and pass them as
    // parameters.
    function setCells(hours) {
        var times = [];

        for (var i = 0; i &lt; cellData.length; i++) {
            var date = moment(cellData[i]).add(hours, 'h').format('MM/DD/YYYY hh:mm a');
            times.push(date);

            myTable.rows[i].cells[1].innerHTML = times[i];
        }
    }

    switch (document.getElementById("sel1").value) {
        case "VIC":
            setCells(1);
            break;
        case "NSW":
            setCells(5);
            break;
    }
}


And a demo of this code in action: https://jsfiddle.net/5q46xu77/1/