JS/jQuery - Sort data by year An AJAX request gives me an object, containing dates and values:

"Values":{"2017-05-01T23:59:27":100.0,"2017-05-02T23:59:27":100.0,"2017-05-03T23:59:27":41.25,"2017-05-04T23:59:27":100.0,...}


The aim is to split this array by year, get all values of a same year together.

The current code is:

var dataPerYear = [];
function addToData(array, nameOfObject, dataToInsert) {
    //Check if the year is already in the array
    var object = $.grep(array, function (e, i) {
        return e.name == nameOfObject;
    });
    // If so, add new data to the correct object
    if (object.length &gt; 0) {
        object[0].values.push(dataToInsert)
    } else
    // If not, create a new object, and add it to the array.
    {
        array.push({name: nameOfObject, values: [dataToInsert]})
    }
}

$(document).ready(function () {
        $.post("myEndPoint", function (data) {
            $.each(data,function (key, val) {
                    addToData(dataPerYear, new Date(key).getFullYear(), val);
            });
        });
});


How can I improve this code, with regards to readability / maintenability first, performance then (not a lot of data, so not a big concern)?
Instead of an array, and having to do a $.grep to check if the year is already in the array, consider using an object. That way, it's a key-value pair, and it's easier and faster to look up. You can convert the data to the final array later on.

Consider using promises instead of callbacks. It's much more flexible and allows better flow control than callbacks.

nameOfObject is misleading when all it is is just the year. Name it to year instead.

There's probably little sense breaking out that function unless something else uses it. It's better to inline operations in this case, making the code easier to trace.

Be wary of the use of new Date. Every time you do that, you create a date object. Since your timestamps are uniformly formatted, you might want to consider slicing off the first 4 characters and use it as year.

Here's an alternative approach. Probably not the most performant, but probably is easier to wrap your head around. Imagine that it's just transformation of data from one form to the other.

$(document).ready(function () {
  $.post("myEndPoint").then(data =&gt; {

    // {"2017-05-01T23:59:27":100.0, ... }
    // to
    // { "2017": [100.0, ...], ... }
    const dataByYear = Object.keys(data).reduce((c, t) =&gt; {
      const year = timestamp.slice(0, 4);
      c[year] = c[year] || [];
      c[year].push(data[t]);
      return c;
    }, {});

    // { "2017": [100.0, ...], ... }
    // to
    // [ { name: "2017", values: [100.0, ...] }, ... ]
    const dataPerYear = Object.keys(dataByYear).map(year =&gt; {
      return { name: year, values: dataByYear[year] }
    });

  })
});