1

I have an array look like:

var v = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"]

What I want to do is sort this dynamically into a new empty array nv. When the sorting is done nv should look like.

var nv = [["07/27/2015", "07/28/2015"], ["08/29/2015", "08/29/2015"], ["07/27/2016"]]

Is it possible to sort like this way?

4
  • what is the criteria? Commented Jul 25, 2015 at 16:22
  • 2
    Group by month, I suppose ... Commented Jul 25, 2015 at 16:23
  • I want to sort the array and make a new inner array if the date is under same month and same year / Group by month and year. Commented Jul 25, 2015 at 16:23
  • Clarify that in the question and title. Commented Jul 25, 2015 at 16:26

3 Answers 3

4
var dates = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];

var groupedDates = dates.reduce(function(l, r) {
    var keyParts = r.split("/"),
        key = keyParts[2] + keyParts[0];

    if (typeof l[key] === "undefined") {
        l[key] = [];
    }

    l[key].push(r);

    return l;
}, {});

var result = Object.keys(groupedDates)
                    .sort(function(a, b) { return Number(a) - Number(b); })
                    .map(function(key) {
                        return groupedDates[key];
                    });

console.log(result);    // [["07/27/2015","07/28/2015"],["08/29/2015","08/29/2015"],["07/27/2016"]]

fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

really clean answer. But not a generic one. What happens when date format is different? or they're a combination of different date formats?
Looks perfect. Thanks again. @Andreas
@Anurag Or the underlying calendar changes, or the human race dies out...^^ Then it has to be adjusted accordingly :) We can only work with the provided informations and they only include one date format. If there will be other date formats I would recommend to use a date library such as momentjs to transform the date strings into real dates. But that would only affect the creation of the object keys.
3

So I made a function that puts the dates into an object whose properties are month and year. A date is put into the property of its month and year. The function then creates an array and creates an inner array for every property of the function. In each inner array it puts all the dates of that property. I figured this approach would be more efficient than nested for loops.

// function takes an array of dates in the following format MM/DD/YYYY
// outputs an array with inner arrays of dates. Each inner array contains dates of the same month and year
var groupDates = function(dateArray) {
    // create object to organize dates by month and year
    var dateHash = {};
    // the array that is outputted
    var groupedDates = [];

    //for every date in dateArray
    dateArray.forEach(function(currentDate) {
        // check if any other dates with the same month and year exist in the dateHash object
        if (dateHash[currentDate.substr(0, 2) + currentDate.substr(6)]) {
            // if other dates exist, push the date to the array in the dateHash property for the dates current month and year
            dateHash[currentDate.substr(0, 2) + currentDate.substr(6)].push(currentDate);
        } else {
            // otherwise create a property for the dates month and year and store the current date in an array in the propery
            dateHash[currentDate.substr(0, 2) + currentDate.substr(6)] = [currentDate];
        }
    });

    // for every propery in the datehash, push the array of dates into the grouped dates array
    for (var dateGroup in dateHash) {
        groupedDates.push(dateHash[dateGroup]);
    }
    return groupedDates;
};

var dateArray = ["07/27/2015", "07/28/2015", "08/29/2015", "08/29/2015", "07/27/2016"];
console.log(groupDates(dateArray));

Comments

0

You can loop over the array and check for each value if it has a new month and year, or it's already included in the sorted array. I think like this untested code:

new_arr = new Array();
for(var i=0; i < v.length; i++){
    var this_date = new Date(v[i]);
    var month_and_year = this_date.getMonth() + this_date.getFullYear();
    if(typeof(new_arr[month_and_year]) == 'undefined'){
         new_arr[month_and_year] = new Array();
    }
    new_arr[month_and_year].push(v[i])
} 

2 Comments

Uncaught TypeError: Cannot read property 'push' of undefined
try typeof(new_arr[month_and_year]) == 'undefined'. I edited the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.