1

I have a array like

var abc = ["mon","Thu","Fri","Tue","Wed","Sun","Sat"]

So next I want these days in order like

["mon","Tue","Wed","Thu","Fri","Sat","Sun"]

Is there any inbuilt functions or any logic for it?

Vicky
  • 147
  • 2
  • 3
  • 9
  • 2
    No, use a date object and then check this out : http://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date – Dhruv Ramani Oct 25 '15 at 06:41
  • 3
    arrays are in hard braces, not curly. – vbranden Oct 25 '15 at 06:43
  • This is object not array.With your current input it is directly not possible to build a logic.what did you attempt? –  Oct 25 '15 at 07:34
  • That is not an object. Anyway, what would be the point in ordering it programmatically when you already know the outcome? Just do `var abc = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];` – JJJ Oct 25 '15 at 08:42
  • @Navoneel I was trying to use switch case statement for this... But it's a lengthy process... – Vicky Oct 25 '15 at 17:39
  • @Vbranden Sorry just wrote it by mistake... – Vicky Oct 25 '15 at 18:49

4 Answers4

0

I used a map object to be used along with a sort function .. pretty easy.

var arrayOfDays = ["Mon","Thu","Fri","Tue","Wed","Sun","Sat"];  //array to be sorted

//int this map, define the "correct" order of days
var map = {
           "Sun" : 0,
           "Mon" : 1,
           "Tue" : 2,
           "Wed" : 3,
           "Thu" : 4,
           "Fri" : 5,
           "Sat" : 6,
        }

function dateSort(array) //function to sort the array
{
    for(i = 0 ; i < array.length ; i++)
        for(j = i + 1 ; j < array.length ; j++)
        {
            if(map[array[i]] > map[array[j]])
            {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
}

It can be invoked as follows:

datesort(arrayOfDays);

I tested it by printing the values of array of dates before calling the function and after:

Before:   Mon Thu Fri Tue Wed Sun Sat

After:    Sun Mon Tue Wed Thu Fri Sat

EDIT: As suggested by others, a version using Array.sort() - though avoid it if you are a beginner.

Define a custom compare function:

function dateCompare(d1, d2)
{
    if(map[d1] == map[d2])
        return 0;
    return (map[d1] < map[d2]) ? -1 : 1;

}

Invoke as:

arrayOfDays.sort(dateCompare);
aditya_medhe
  • 195
  • 15
  • Use the Array.sort function next time please. It looks better and abit more efficient – Ori Refael Oct 25 '15 at 08:53
  • It cannot be done with plain Array.sort(). Please read the code carefully. The sorting algorithm compares each element with it's correct order in the map.. and not the actual element. It can be done by using a compare function, but the OP seems a beginner hence I avoided it in order to keep it simple. – aditya_medhe Oct 25 '15 at 08:54
  • @aditya_m: It can be done with Array.sort(comparefunction) – trincot Oct 25 '15 at 08:57
  • @aditya_m: Of course it *can* and should be done with `Array.sort`. You are passing in a callback, you can tell it exactly what to do. It's actually quite trivial: https://jsfiddle.net/0bcpkfd2/ – Jon Oct 25 '15 at 08:57
  • I know that Array.sort is the best practice to do it. But OP hasn't yet learned the syntax of declaring an array, so I assumed that he/she is a beginner. Please read my edited comment. – aditya_medhe Oct 25 '15 at 09:01
  • Its ok if OP didnt know it, this is where you learn things, using code's best practices. As others said, it can easily be done with Array.Sort if comparing number value from the map object. In addition to guide the OP, its important that answer will be provided with a 'fine' code. – Ori Refael Oct 25 '15 at 13:00
  • I wrote the answer as I saw fit. Due to request by many people, I edited it to include Arrays.sort. I hope you are okay with it. If not, please feel free to add an answer containing a code that matches your expectations. – aditya_medhe Oct 25 '15 at 14:48
  • @Vicky the strings can be converted to numbers and be sorted this way. Read previous comments. – Ori Refael Oct 25 '15 at 21:08
0

As indicated by others, you need to use square brackets for arrays, not curly ones:

var abc = ["mon","Thu","Fri","Tue","Wed","Sun","Sat"];

There is no predefined method that recognizes weekdays, but you can just compare given day names to a list that is in the correct order, like this:

function compareDayNames(day1, day2) {
    var weekdays = ',monday,tuesday,wednesday,thursday,friday,saturday,sunday';
    return weekdays.indexOf(',' + day1.toLowerCase())
            - weekdays.indexOf(',' + day2.toLowerCase());
}

var abc = ["mon","Thu","Fri","Tue","Wed","Sun","Sat"];

abc.sort(compareDayNames);

console.log('Sorted: ' + abc.join(','));

Output in the console is:

Sorted: mon,Tue,Wed,Thu,Fri,Sat,Sun

This function also sorts longer and shorter names well:

var abc = ['Satur','Tu', 'W', 'M', 'Thurs'];
abc.sort(compareDayNames);

console.log('Sorted: ' + abc.join(','));

Output:

Sorted: M,Tu,W,Thurs,Satur

EDIT:

If you want to throw an error when an invalid day name is provided, or a name that is less than 2 characters (because T and S are ambiguous), then rewrite the compare function as follows:

function compareDayNames(day1, day2) {
    var weekdays = ',monday,tuesday,wednesday,thursday,friday,saturday,sunday';

    function dayNumber(day) {
        var pos = weekdays.indexOf(',' + day.toLowerCase());
        if (pos === -1 || day.length < 2) {
            throw '"' + day + '" is not a valid day name';
        }
        return pos;
    }

    return dayNumber(day1) - dayNumber(day2);
}
trincot
  • 211,288
  • 25
  • 175
  • 211
  • Since you are using single character day names as well, what will be the output for `M W T S F T S`? – aditya_medhe Oct 25 '15 at 09:27
  • The output will be M,T,T,W,F,S,S. Of course, T and S are ambiguous, and are taken to be Tuesday and Saturday. Just don't use them like you would not use them in real life "I have an appointment on T" could lead to disappointments. – trincot Oct 25 '15 at 09:34
  • Right. Perhaps you could keep the minimum input length to 2 to avoid ambiguity. Then it would be a truly versatile function. – aditya_medhe Oct 25 '15 at 09:38
  • What would you want to happen when the input length is 1 of one or more values? Remove them from the array? – trincot Oct 25 '15 at 09:42
  • Of course not. The right way to handle it gracefully would be to throw an error... – aditya_medhe Oct 25 '15 at 09:48
  • I have added this now in my answer. The compare function will now throw an error in that case, and also when a completely invalid name is provided, like 'XXX'. If you find the answer satisfactory, please accept it. Thanks :) – trincot Oct 25 '15 at 09:58
  • Great.. I would have accepted it, had I been the OP :) – aditya_medhe Oct 25 '15 at 10:00
0

There is no inbuilt function for it, you need to write your own logic as suggested in other answers. You can create one common function to compare two array's as...

function compareDays(wrongSquence , rightSequence) {
   var i=0;
   for(i=0;i<wrongSquence.length;i++) {
      if(wrongSquence [i] != rightSequence[i]) {       
          wrongSquence [i] = rightSequence[i];
      }
   } 
   return wrongSquence;
}

//e.g....
var abc = ["mon","Thu","Fri","Tue","Wed","Sun","Sat"],
outputFormat = ["mon","Tue","Wed","Thu","Fri","Sat","Sun"];

var correctArray = compareDays(abc, outputFormat);
console.log(correctArray);  // check output...
Rohit416
  • 3,114
  • 3
  • 21
  • 38
UnmeshD
  • 159
  • 2
  • 11
  • Try to format only code as code, not your whole post. – trincot Oct 25 '15 at 10:00
  • 1
    What if you call the function with fewer days, like ['Sat', 'Thu', 'Fri']? Should it not just sort them to ['Thu', 'Fri', 'Sat']? – trincot Oct 25 '15 at 10:03
  • Yes , this function will sort them., for that you need to give two paramenter sas compareDays(['Sat', 'Thu', 'Fri'],['Thu', 'Fri', 'Sat']); – UnmeshD Oct 25 '15 at 10:17
  • What is the use of a function if you have to provide it the right answer in every call? You might as well do this then: `correct = abc.join(',') === 'Thu,Fri,Sat'`. No need for a function. – trincot Oct 25 '15 at 10:24
0
$(document).ready(function () {
            var ndays = "";
            var days = "Sat,Fri,mon,Thu,Tue,Wed,Sun";
            var dys = days.split(",");
            debugger;
            for (var i = 0; i < dys.length; i++) {
                switch (dys[i]) {
                    case "mon":
                        ndays = ndays + ",1";
                        break;
                    case "Tue":
                        ndays = ndays + ",2";
                        break;
                    case "Wed":
                        ndays = ndays + ",3";
                        break;
                    case "Thu":
                        ndays = ndays + ",4";
                        break;
                    case "Fri":
                        ndays = ndays + ",5";
                        break;
                    case "Sat":
                        ndays = ndays + ",6";
                        break;
                    default:
                        ndays = ndays + ",7";
                        break;
                }
                alert(ndays);
            }
            var cDays = "";

            var wdays = ndays.split(",").sort();

            for (var s = 0; s < wdays.length; s++) {
                //alert(wdays[s]);
                debugger;
                if (wdays[s] === "1") {
                    cDays = "Mon";
                }
                else if (wdays[s] === "2") {
                    cDays = cDays + ",Tue";
                }
                else if (wdays[s] === "3") {
                    cDays = cDays + ",Wed";
                }
                else if (wdays[s] === "4") {
                    cDays = cDays + ",Thu";
                }
                else if (wdays[s] === "5") {
                    cDays = cDays + ",Fri";
                }
                else if (wdays[s] === "6") {
                    cDays = cDays + ",Sat";
                }
                else {
                    cDays = cDays + ",Sun";
                }
            }
        });
Sidhu
  • 1