Sort an array which contains number and strings












14














I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.



var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result


I have also tried



var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result









share|improve this question
























  • Is there any reason for "2" and "3" to be after 9? For that kind of sort, you can either sort twice or make a single unique complex sort.
    – briosheje
    Dec 28 '18 at 12:20










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    Dec 28 '18 at 12:21






  • 2




    @briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
    – Nick Parsons
    Dec 28 '18 at 12:21












  • How should the "numbers as strings" be sorted? As nbers or as strings?
    – Jonas Wilms
    Dec 29 '18 at 13:27
















14














I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.



var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result


I have also tried



var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result









share|improve this question
























  • Is there any reason for "2" and "3" to be after 9? For that kind of sort, you can either sort twice or make a single unique complex sort.
    – briosheje
    Dec 28 '18 at 12:20










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    Dec 28 '18 at 12:21






  • 2




    @briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
    – Nick Parsons
    Dec 28 '18 at 12:21












  • How should the "numbers as strings" be sorted? As nbers or as strings?
    – Jonas Wilms
    Dec 29 '18 at 13:27














14












14








14







I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.



var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result


I have also tried



var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result









share|improve this question















I am trying to sort an array which contains strings, numbers, and numbers as strings (ex. '1','2'). I want to sort this array so that the sorted array contains numbers first and then strings that contain a number and then finally strings.



var arr = [9,5,'2','ab','3',-1 ] // to be sorted
arr.sort()
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
//arr = [-1, "2", 5, 9, "ab"] // actual result


I have also tried



var number =;
var char =;
arr.forEach(a=>{
if(typeof a == 'number') number.push(a);
else char.push(a);
})
arr = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))
// arr = [-1, 5, 9, "2", "3","ab"] // expected result
// arr = [-1, 5, 9, "2", "ab", "3"]// actual result






javascript arrays string numbers






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '18 at 12:36

























asked Dec 28 '18 at 12:11









Komal Bansal

2218




2218












  • Is there any reason for "2" and "3" to be after 9? For that kind of sort, you can either sort twice or make a single unique complex sort.
    – briosheje
    Dec 28 '18 at 12:20










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    Dec 28 '18 at 12:21






  • 2




    @briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
    – Nick Parsons
    Dec 28 '18 at 12:21












  • How should the "numbers as strings" be sorted? As nbers or as strings?
    – Jonas Wilms
    Dec 29 '18 at 13:27


















  • Is there any reason for "2" and "3" to be after 9? For that kind of sort, you can either sort twice or make a single unique complex sort.
    – briosheje
    Dec 28 '18 at 12:20










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    Dec 28 '18 at 12:21






  • 2




    @briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
    – Nick Parsons
    Dec 28 '18 at 12:21












  • How should the "numbers as strings" be sorted? As nbers or as strings?
    – Jonas Wilms
    Dec 29 '18 at 13:27
















Is there any reason for "2" and "3" to be after 9? For that kind of sort, you can either sort twice or make a single unique complex sort.
– briosheje
Dec 28 '18 at 12:20




Is there any reason for "2" and "3" to be after 9? For that kind of sort, you can either sort twice or make a single unique complex sort.
– briosheje
Dec 28 '18 at 12:20












@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21




@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
Dec 28 '18 at 12:21




2




2




@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21






@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
Dec 28 '18 at 12:21














How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27




How should the "numbers as strings" be sorted? As nbers or as strings?
– Jonas Wilms
Dec 29 '18 at 13:27












8 Answers
8






active

oldest

votes


















1














It seems you have done most of the work in your second attempt.
All I have done here is used Array.concat to join the sorted results of number and char together.






var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
var number = ;
var char = ;
arr.forEach(a => {
if (typeof a == 'number') number.push(a);
else char.push(a);
})


var sorted = number.sort().concat(char.sort());
console.log(sorted)








share|improve this answer





















  • Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
    – Komal Bansal
    Dec 28 '18 at 12:35






  • 3




    @komal a>b returns true or false whereas a number is expected
    – Jonas Wilms
    Dec 28 '18 at 12:42



















17














The shortest is probably:



 arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));





share|improve this answer























  • It doesn't sort the string numbers though. Should it?
    – NikxDa
    Dec 29 '18 at 4:06










  • @nikxda it actually should
    – Jonas Wilms
    Dec 29 '18 at 10:19










  • Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
    – NikxDa
    Dec 29 '18 at 13:24










  • @NikxDa well it sorts them lexicographically, not sure if that is wanted
    – Jonas Wilms
    Dec 29 '18 at 13:31



















7














You can sort the integers first and then the non-integers by using .filter() to separate both data-types.



See working example below (read code comments for explanation):






const arr = [9,5,'2','ab','3',-1];

const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]








share|improve this answer



















  • 2




    performance here is bad. Jonas's solution wraps it up with a single sort.
    – Jony-Y
    Dec 28 '18 at 13:41






  • 5




    On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
    – YSC
    Dec 28 '18 at 14:34








  • 2




    @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
    – Jonas Wilms
    Dec 28 '18 at 15:44












  • @JonasWilms To have the same effect, it should be !== "number".
    – wizzwizz4
    Dec 28 '18 at 15:46










  • not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
    – Jony-Y
    Dec 28 '18 at 15:49



















2














Here you are!






const arr = [9,5,'2','ab','3',-1 ]

const numbers = arr.filter(i => typeof i === 'number');
const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

numbers.sort();
numerics.sort();
strings.sort()

const result = .concat(numbers, numerics, strings)

console.log(result)





My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.






share|improve this answer





























    1














    Try using this:






     

    var arr = [9,5,'2','ab','3',-1 ];
    var number = ;
    var strInt = ;
    var char = ;
    arr.forEach(a => {
    if (typeof a === "number") {
    number.push(a);
    } else if (typeof a === "string" && /d/.test(a)) {
    strInt.push(a);
    } else {
    char.push(a);
    }
    });
    arr = number.concat(strInt.concat(char));
    console.log(arr);





    What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.






    share|improve this answer























    • @NurbolAlpysbayev Fixed now.
      – Jack Bashford
      Dec 28 '18 at 12:30





















    1














    Try this






    const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
    const sortedArr = arr.sort((a, b) => {
    if (typeof a === 'number' && typeof b === 'number') {
    return a - b;
    } else if (typeof a === 'number') {
    return -1;
    } else if (typeof b === 'number') {
    return 1;
    } else {
    return a > b ? 1 : -1;
    }
    });

    console.log(sortedArr);





    This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.






    share|improve this answer























    • Explanation added with a link to MDN.
      – Sergio Tx
      Dec 28 '18 at 12:34



















    0














    var arr=[9,5,'2','ab','3',-1];
    var string_arr=;
    var number_arr=;
    var string_number_arr=;
    for(var i=0;i<arr.length;i++)
    {

    if(typeof(arr[i])=='number')
    {
    number_arr.push(arr[i]);

    }
    else if((Number(arr[i]).toString())=="NaN")
    {
    string_number_arr.push(arr[i]);

    }
    else
    {
    string_arr.push(arr[i]);
    }

    }
    string_arr.sort();
    number_arr.sort();
    string_number_arr.sort();
    var arr=number_arr.concat(string_arr,string_number_arr);
    console.log(arr);





    share|improve this answer





























      0














      You can use Array .sort() method anyway.



      You just need to provide a function to control sorting criteria for every comparsion.



      Example:



      // First of all discretize all kinds of data you want to deal with
      function typeClassify(v) {
      return typeof v == "number"
      ? "N"
      : isNaN(v) ? "s" : "n"
      // (Treat all non numeric values as strings)
      ;
      };


      // Second: implement the sorting function
      function sortCriteria(a, b) {
      var mode = typeClassify(a) + typeClassify(b);
      switch (mode) {
      case "NN":
      return a - b;
      case "nn":
      return Number(a) - Number(b);
      case "ss":
      return a == b
      ? 0
      : a > b
      ? -1 : 1
      ;
      case "Nn":
      case "Ns":
      case "ns":
      return -1;
      case "nN":
      case "sN":
      case "sn":
      return 1;
      default:
      throw "This must never happen";
      };
      };

      // And finally provide that function as a callback for .sort() method
      var arr = [9,5,'2','ab','3',-1 ] // to be sorted
      console.log(arr.sort(sortCriteria));

      // arr = [-1, 5, 9, "2", "3","ab"] // expected result
      // arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result


      Obviously the functionality of typeClassify() function can be flattened into sortCriteria() to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958419%2fsort-an-array-which-contains-number-and-strings%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        8 Answers
        8






        active

        oldest

        votes








        8 Answers
        8






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        It seems you have done most of the work in your second attempt.
        All I have done here is used Array.concat to join the sorted results of number and char together.






        var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
        var number = ;
        var char = ;
        arr.forEach(a => {
        if (typeof a == 'number') number.push(a);
        else char.push(a);
        })


        var sorted = number.sort().concat(char.sort());
        console.log(sorted)








        share|improve this answer





















        • Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
          – Komal Bansal
          Dec 28 '18 at 12:35






        • 3




          @komal a>b returns true or false whereas a number is expected
          – Jonas Wilms
          Dec 28 '18 at 12:42
















        1














        It seems you have done most of the work in your second attempt.
        All I have done here is used Array.concat to join the sorted results of number and char together.






        var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
        var number = ;
        var char = ;
        arr.forEach(a => {
        if (typeof a == 'number') number.push(a);
        else char.push(a);
        })


        var sorted = number.sort().concat(char.sort());
        console.log(sorted)








        share|improve this answer





















        • Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
          – Komal Bansal
          Dec 28 '18 at 12:35






        • 3




          @komal a>b returns true or false whereas a number is expected
          – Jonas Wilms
          Dec 28 '18 at 12:42














        1












        1








        1






        It seems you have done most of the work in your second attempt.
        All I have done here is used Array.concat to join the sorted results of number and char together.






        var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
        var number = ;
        var char = ;
        arr.forEach(a => {
        if (typeof a == 'number') number.push(a);
        else char.push(a);
        })


        var sorted = number.sort().concat(char.sort());
        console.log(sorted)








        share|improve this answer












        It seems you have done most of the work in your second attempt.
        All I have done here is used Array.concat to join the sorted results of number and char together.






        var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
        var number = ;
        var char = ;
        arr.forEach(a => {
        if (typeof a == 'number') number.push(a);
        else char.push(a);
        })


        var sorted = number.sort().concat(char.sort());
        console.log(sorted)








        var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
        var number = ;
        var char = ;
        arr.forEach(a => {
        if (typeof a == 'number') number.push(a);
        else char.push(a);
        })


        var sorted = number.sort().concat(char.sort());
        console.log(sorted)





        var arr = [9, 5, '2', 'ab', '3', -1] // to be sorted
        var number = ;
        var char = ;
        arr.forEach(a => {
        if (typeof a == 'number') number.push(a);
        else char.push(a);
        })


        var sorted = number.sort().concat(char.sort());
        console.log(sorted)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 28 '18 at 12:25









        ksav

        4,17021328




        4,17021328












        • Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
          – Komal Bansal
          Dec 28 '18 at 12:35






        • 3




          @komal a>b returns true or false whereas a number is expected
          – Jonas Wilms
          Dec 28 '18 at 12:42


















        • Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
          – Komal Bansal
          Dec 28 '18 at 12:35






        • 3




          @komal a>b returns true or false whereas a number is expected
          – Jonas Wilms
          Dec 28 '18 at 12:42
















        Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
        – Komal Bansal
        Dec 28 '18 at 12:35




        Hi , I have tried this "result = (number.sort((a,b)=> a>b)).concat(char.sort((a,b)=> a>b))". But i didn't get the expected output. Could you tell me how these two are different
        – Komal Bansal
        Dec 28 '18 at 12:35




        3




        3




        @komal a>b returns true or false whereas a number is expected
        – Jonas Wilms
        Dec 28 '18 at 12:42




        @komal a>b returns true or false whereas a number is expected
        – Jonas Wilms
        Dec 28 '18 at 12:42













        17














        The shortest is probably:



         arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));





        share|improve this answer























        • It doesn't sort the string numbers though. Should it?
          – NikxDa
          Dec 29 '18 at 4:06










        • @nikxda it actually should
          – Jonas Wilms
          Dec 29 '18 at 10:19










        • Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
          – NikxDa
          Dec 29 '18 at 13:24










        • @NikxDa well it sorts them lexicographically, not sure if that is wanted
          – Jonas Wilms
          Dec 29 '18 at 13:31
















        17














        The shortest is probably:



         arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));





        share|improve this answer























        • It doesn't sort the string numbers though. Should it?
          – NikxDa
          Dec 29 '18 at 4:06










        • @nikxda it actually should
          – Jonas Wilms
          Dec 29 '18 at 10:19










        • Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
          – NikxDa
          Dec 29 '18 at 13:24










        • @NikxDa well it sorts them lexicographically, not sure if that is wanted
          – Jonas Wilms
          Dec 29 '18 at 13:31














        17












        17








        17






        The shortest is probably:



         arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));





        share|improve this answer














        The shortest is probably:



         arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 28 '18 at 13:22

























        answered Dec 28 '18 at 12:41









        Jonas Wilms

        55.4k42750




        55.4k42750












        • It doesn't sort the string numbers though. Should it?
          – NikxDa
          Dec 29 '18 at 4:06










        • @nikxda it actually should
          – Jonas Wilms
          Dec 29 '18 at 10:19










        • Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
          – NikxDa
          Dec 29 '18 at 13:24










        • @NikxDa well it sorts them lexicographically, not sure if that is wanted
          – Jonas Wilms
          Dec 29 '18 at 13:31


















        • It doesn't sort the string numbers though. Should it?
          – NikxDa
          Dec 29 '18 at 4:06










        • @nikxda it actually should
          – Jonas Wilms
          Dec 29 '18 at 10:19










        • Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
          – NikxDa
          Dec 29 '18 at 13:24










        • @NikxDa well it sorts them lexicographically, not sure if that is wanted
          – Jonas Wilms
          Dec 29 '18 at 13:31
















        It doesn't sort the string numbers though. Should it?
        – NikxDa
        Dec 29 '18 at 4:06




        It doesn't sort the string numbers though. Should it?
        – NikxDa
        Dec 29 '18 at 4:06












        @nikxda it actually should
        – Jonas Wilms
        Dec 29 '18 at 10:19




        @nikxda it actually should
        – Jonas Wilms
        Dec 29 '18 at 10:19












        Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
        – NikxDa
        Dec 29 '18 at 13:24




        Having this array: ["a", "5", "1", "-1", 17, "abc", 23, -5, 0, "17"] sorts the "17" before the "5".
        – NikxDa
        Dec 29 '18 at 13:24












        @NikxDa well it sorts them lexicographically, not sure if that is wanted
        – Jonas Wilms
        Dec 29 '18 at 13:31




        @NikxDa well it sorts them lexicographically, not sure if that is wanted
        – Jonas Wilms
        Dec 29 '18 at 13:31











        7














        You can sort the integers first and then the non-integers by using .filter() to separate both data-types.



        See working example below (read code comments for explanation):






        const arr = [9,5,'2','ab','3',-1];

        const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
        const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

        const res = [...nums, ...non_nums]; // combine the two arrays
        console.log(res); // [-1, 5, 9, "2", "3", "ab"]








        share|improve this answer



















        • 2




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          Dec 28 '18 at 13:41






        • 5




          On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
          – YSC
          Dec 28 '18 at 14:34








        • 2




          @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
          – Jonas Wilms
          Dec 28 '18 at 15:44












        • @JonasWilms To have the same effect, it should be !== "number".
          – wizzwizz4
          Dec 28 '18 at 15:46










        • not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
          – Jony-Y
          Dec 28 '18 at 15:49
















        7














        You can sort the integers first and then the non-integers by using .filter() to separate both data-types.



        See working example below (read code comments for explanation):






        const arr = [9,5,'2','ab','3',-1];

        const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
        const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

        const res = [...nums, ...non_nums]; // combine the two arrays
        console.log(res); // [-1, 5, 9, "2", "3", "ab"]








        share|improve this answer



















        • 2




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          Dec 28 '18 at 13:41






        • 5




          On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
          – YSC
          Dec 28 '18 at 14:34








        • 2




          @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
          – Jonas Wilms
          Dec 28 '18 at 15:44












        • @JonasWilms To have the same effect, it should be !== "number".
          – wizzwizz4
          Dec 28 '18 at 15:46










        • not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
          – Jony-Y
          Dec 28 '18 at 15:49














        7












        7








        7






        You can sort the integers first and then the non-integers by using .filter() to separate both data-types.



        See working example below (read code comments for explanation):






        const arr = [9,5,'2','ab','3',-1];

        const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
        const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

        const res = [...nums, ...non_nums]; // combine the two arrays
        console.log(res); // [-1, 5, 9, "2", "3", "ab"]








        share|improve this answer














        You can sort the integers first and then the non-integers by using .filter() to separate both data-types.



        See working example below (read code comments for explanation):






        const arr = [9,5,'2','ab','3',-1];

        const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
        const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

        const res = [...nums, ...non_nums]; // combine the two arrays
        console.log(res); // [-1, 5, 9, "2", "3", "ab"]








        const arr = [9,5,'2','ab','3',-1];

        const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
        const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

        const res = [...nums, ...non_nums]; // combine the two arrays
        console.log(res); // [-1, 5, 9, "2", "3", "ab"]





        const arr = [9,5,'2','ab','3',-1];

        const nums = arr.filter(n => typeof n == "number").sort(); // If the data type of a given element is a number store it in this array (and then sort)
        const non_nums = arr.filter(x => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

        const res = [...nums, ...non_nums]; // combine the two arrays
        console.log(res); // [-1, 5, 9, "2", "3", "ab"]






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 28 '18 at 16:00

























        answered Dec 28 '18 at 12:30









        Nick Parsons

        4,8222721




        4,8222721








        • 2




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          Dec 28 '18 at 13:41






        • 5




          On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
          – YSC
          Dec 28 '18 at 14:34








        • 2




          @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
          – Jonas Wilms
          Dec 28 '18 at 15:44












        • @JonasWilms To have the same effect, it should be !== "number".
          – wizzwizz4
          Dec 28 '18 at 15:46










        • not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
          – Jony-Y
          Dec 28 '18 at 15:49














        • 2




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          Dec 28 '18 at 13:41






        • 5




          On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
          – YSC
          Dec 28 '18 at 14:34








        • 2




          @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
          – Jonas Wilms
          Dec 28 '18 at 15:44












        • @JonasWilms To have the same effect, it should be !== "number".
          – wizzwizz4
          Dec 28 '18 at 15:46










        • not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
          – Jony-Y
          Dec 28 '18 at 15:49








        2




        2




        performance here is bad. Jonas's solution wraps it up with a single sort.
        – Jony-Y
        Dec 28 '18 at 13:41




        performance here is bad. Jonas's solution wraps it up with a single sort.
        – Jony-Y
        Dec 28 '18 at 13:41




        5




        5




        On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
        – YSC
        Dec 28 '18 at 14:34






        On the contrary, performance is better. This is called divide and conquer. Since sorting is usually O(n.log(n)), making 2 sorts of cardinal n is better than making one sort of cardinal 2n. Anyway, arguing about performance for sorting a few items is pointless.
        – YSC
        Dec 28 '18 at 14:34






        2




        2




        @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
        – Jonas Wilms
        Dec 28 '18 at 15:44






        @Jony-Y disagree. If nums.includes(x) would be replaced with typeof x === "string" it would be significantly faster (but it takes more memory) [in theory, performance in JS is always a non-deterministic thing]
        – Jonas Wilms
        Dec 28 '18 at 15:44














        @JonasWilms To have the same effect, it should be !== "number".
        – wizzwizz4
        Dec 28 '18 at 15:46




        @JonasWilms To have the same effect, it should be !== "number".
        – wizzwizz4
        Dec 28 '18 at 15:46












        not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
        – Jony-Y
        Dec 28 '18 at 15:49




        not sure you're correct here, you have to pay O(n) then O(mlogm) then O(n*m) then O(plogp) where as in the other solution you have to pay nlogn
        – Jony-Y
        Dec 28 '18 at 15:49











        2














        Here you are!






        const arr = [9,5,'2','ab','3',-1 ]

        const numbers = arr.filter(i => typeof i === 'number');
        const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
        const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

        numbers.sort();
        numerics.sort();
        strings.sort()

        const result = .concat(numbers, numerics, strings)

        console.log(result)





        My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.






        share|improve this answer


























          2














          Here you are!






          const arr = [9,5,'2','ab','3',-1 ]

          const numbers = arr.filter(i => typeof i === 'number');
          const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
          const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

          numbers.sort();
          numerics.sort();
          strings.sort()

          const result = .concat(numbers, numerics, strings)

          console.log(result)





          My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.






          share|improve this answer
























            2












            2








            2






            Here you are!






            const arr = [9,5,'2','ab','3',-1 ]

            const numbers = arr.filter(i => typeof i === 'number');
            const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
            const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

            numbers.sort();
            numerics.sort();
            strings.sort()

            const result = .concat(numbers, numerics, strings)

            console.log(result)





            My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.






            share|improve this answer












            Here you are!






            const arr = [9,5,'2','ab','3',-1 ]

            const numbers = arr.filter(i => typeof i === 'number');
            const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
            const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

            numbers.sort();
            numerics.sort();
            strings.sort()

            const result = .concat(numbers, numerics, strings)

            console.log(result)





            My strategy was to first find all the three chunks (numbers, numerics and strings), then just concatting them.






            const arr = [9,5,'2','ab','3',-1 ]

            const numbers = arr.filter(i => typeof i === 'number');
            const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
            const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

            numbers.sort();
            numerics.sort();
            strings.sort()

            const result = .concat(numbers, numerics, strings)

            console.log(result)





            const arr = [9,5,'2','ab','3',-1 ]

            const numbers = arr.filter(i => typeof i === 'number');
            const numerics = arr.filter(i => typeof i === 'string' && !isNaN(i));
            const strings = arr.filter(i => typeof i === 'string' && isNaN(i));

            numbers.sort();
            numerics.sort();
            strings.sort()

            const result = .concat(numbers, numerics, strings)

            console.log(result)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 28 '18 at 12:23









            Nurbol Alpysbayev

            3,7391227




            3,7391227























                1














                Try using this:






                 

                var arr = [9,5,'2','ab','3',-1 ];
                var number = ;
                var strInt = ;
                var char = ;
                arr.forEach(a => {
                if (typeof a === "number") {
                number.push(a);
                } else if (typeof a === "string" && /d/.test(a)) {
                strInt.push(a);
                } else {
                char.push(a);
                }
                });
                arr = number.concat(strInt.concat(char));
                console.log(arr);





                What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.






                share|improve this answer























                • @NurbolAlpysbayev Fixed now.
                  – Jack Bashford
                  Dec 28 '18 at 12:30


















                1














                Try using this:






                 

                var arr = [9,5,'2','ab','3',-1 ];
                var number = ;
                var strInt = ;
                var char = ;
                arr.forEach(a => {
                if (typeof a === "number") {
                number.push(a);
                } else if (typeof a === "string" && /d/.test(a)) {
                strInt.push(a);
                } else {
                char.push(a);
                }
                });
                arr = number.concat(strInt.concat(char));
                console.log(arr);





                What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.






                share|improve this answer























                • @NurbolAlpysbayev Fixed now.
                  – Jack Bashford
                  Dec 28 '18 at 12:30
















                1












                1








                1






                Try using this:






                 

                var arr = [9,5,'2','ab','3',-1 ];
                var number = ;
                var strInt = ;
                var char = ;
                arr.forEach(a => {
                if (typeof a === "number") {
                number.push(a);
                } else if (typeof a === "string" && /d/.test(a)) {
                strInt.push(a);
                } else {
                char.push(a);
                }
                });
                arr = number.concat(strInt.concat(char));
                console.log(arr);





                What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.






                share|improve this answer














                Try using this:






                 

                var arr = [9,5,'2','ab','3',-1 ];
                var number = ;
                var strInt = ;
                var char = ;
                arr.forEach(a => {
                if (typeof a === "number") {
                number.push(a);
                } else if (typeof a === "string" && /d/.test(a)) {
                strInt.push(a);
                } else {
                char.push(a);
                }
                });
                arr = number.concat(strInt.concat(char));
                console.log(arr);





                What this does is makes three arrays, one for numbers, one for strings containing numbers, and one for strings. It sorts each element into the appropriate array, then finally concatenates them all together in the correct order.






                 

                var arr = [9,5,'2','ab','3',-1 ];
                var number = ;
                var strInt = ;
                var char = ;
                arr.forEach(a => {
                if (typeof a === "number") {
                number.push(a);
                } else if (typeof a === "string" && /d/.test(a)) {
                strInt.push(a);
                } else {
                char.push(a);
                }
                });
                arr = number.concat(strInt.concat(char));
                console.log(arr);





                 

                var arr = [9,5,'2','ab','3',-1 ];
                var number = ;
                var strInt = ;
                var char = ;
                arr.forEach(a => {
                if (typeof a === "number") {
                number.push(a);
                } else if (typeof a === "string" && /d/.test(a)) {
                strInt.push(a);
                } else {
                char.push(a);
                }
                });
                arr = number.concat(strInt.concat(char));
                console.log(arr);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 28 '18 at 12:30

























                answered Dec 28 '18 at 12:25









                Jack Bashford

                5,56631235




                5,56631235












                • @NurbolAlpysbayev Fixed now.
                  – Jack Bashford
                  Dec 28 '18 at 12:30




















                • @NurbolAlpysbayev Fixed now.
                  – Jack Bashford
                  Dec 28 '18 at 12:30


















                @NurbolAlpysbayev Fixed now.
                – Jack Bashford
                Dec 28 '18 at 12:30






                @NurbolAlpysbayev Fixed now.
                – Jack Bashford
                Dec 28 '18 at 12:30













                1














                Try this






                const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
                const sortedArr = arr.sort((a, b) => {
                if (typeof a === 'number' && typeof b === 'number') {
                return a - b;
                } else if (typeof a === 'number') {
                return -1;
                } else if (typeof b === 'number') {
                return 1;
                } else {
                return a > b ? 1 : -1;
                }
                });

                console.log(sortedArr);





                This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.






                share|improve this answer























                • Explanation added with a link to MDN.
                  – Sergio Tx
                  Dec 28 '18 at 12:34
















                1














                Try this






                const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
                const sortedArr = arr.sort((a, b) => {
                if (typeof a === 'number' && typeof b === 'number') {
                return a - b;
                } else if (typeof a === 'number') {
                return -1;
                } else if (typeof b === 'number') {
                return 1;
                } else {
                return a > b ? 1 : -1;
                }
                });

                console.log(sortedArr);





                This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.






                share|improve this answer























                • Explanation added with a link to MDN.
                  – Sergio Tx
                  Dec 28 '18 at 12:34














                1












                1








                1






                Try this






                const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
                const sortedArr = arr.sort((a, b) => {
                if (typeof a === 'number' && typeof b === 'number') {
                return a - b;
                } else if (typeof a === 'number') {
                return -1;
                } else if (typeof b === 'number') {
                return 1;
                } else {
                return a > b ? 1 : -1;
                }
                });

                console.log(sortedArr);





                This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.






                share|improve this answer














                Try this






                const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
                const sortedArr = arr.sort((a, b) => {
                if (typeof a === 'number' && typeof b === 'number') {
                return a - b;
                } else if (typeof a === 'number') {
                return -1;
                } else if (typeof b === 'number') {
                return 1;
                } else {
                return a > b ? 1 : -1;
                }
                });

                console.log(sortedArr);





                This uses the Array.prototype.sort optional function to sort elements in one array. It must return a number. If the number > 0, b goes first. If the number < 0, a goes first. If it's 0, their position remains unchanged.






                const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
                const sortedArr = arr.sort((a, b) => {
                if (typeof a === 'number' && typeof b === 'number') {
                return a - b;
                } else if (typeof a === 'number') {
                return -1;
                } else if (typeof b === 'number') {
                return 1;
                } else {
                return a > b ? 1 : -1;
                }
                });

                console.log(sortedArr);





                const arr = [9, 5, '2', 'ab', '3', 'AB', -1];
                const sortedArr = arr.sort((a, b) => {
                if (typeof a === 'number' && typeof b === 'number') {
                return a - b;
                } else if (typeof a === 'number') {
                return -1;
                } else if (typeof b === 'number') {
                return 1;
                } else {
                return a > b ? 1 : -1;
                }
                });

                console.log(sortedArr);






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 28 '18 at 12:43

























                answered Dec 28 '18 at 12:23









                Sergio Tx

                1,6731020




                1,6731020












                • Explanation added with a link to MDN.
                  – Sergio Tx
                  Dec 28 '18 at 12:34


















                • Explanation added with a link to MDN.
                  – Sergio Tx
                  Dec 28 '18 at 12:34
















                Explanation added with a link to MDN.
                – Sergio Tx
                Dec 28 '18 at 12:34




                Explanation added with a link to MDN.
                – Sergio Tx
                Dec 28 '18 at 12:34











                0














                var arr=[9,5,'2','ab','3',-1];
                var string_arr=;
                var number_arr=;
                var string_number_arr=;
                for(var i=0;i<arr.length;i++)
                {

                if(typeof(arr[i])=='number')
                {
                number_arr.push(arr[i]);

                }
                else if((Number(arr[i]).toString())=="NaN")
                {
                string_number_arr.push(arr[i]);

                }
                else
                {
                string_arr.push(arr[i]);
                }

                }
                string_arr.sort();
                number_arr.sort();
                string_number_arr.sort();
                var arr=number_arr.concat(string_arr,string_number_arr);
                console.log(arr);





                share|improve this answer


























                  0














                  var arr=[9,5,'2','ab','3',-1];
                  var string_arr=;
                  var number_arr=;
                  var string_number_arr=;
                  for(var i=0;i<arr.length;i++)
                  {

                  if(typeof(arr[i])=='number')
                  {
                  number_arr.push(arr[i]);

                  }
                  else if((Number(arr[i]).toString())=="NaN")
                  {
                  string_number_arr.push(arr[i]);

                  }
                  else
                  {
                  string_arr.push(arr[i]);
                  }

                  }
                  string_arr.sort();
                  number_arr.sort();
                  string_number_arr.sort();
                  var arr=number_arr.concat(string_arr,string_number_arr);
                  console.log(arr);





                  share|improve this answer
























                    0












                    0








                    0






                    var arr=[9,5,'2','ab','3',-1];
                    var string_arr=;
                    var number_arr=;
                    var string_number_arr=;
                    for(var i=0;i<arr.length;i++)
                    {

                    if(typeof(arr[i])=='number')
                    {
                    number_arr.push(arr[i]);

                    }
                    else if((Number(arr[i]).toString())=="NaN")
                    {
                    string_number_arr.push(arr[i]);

                    }
                    else
                    {
                    string_arr.push(arr[i]);
                    }

                    }
                    string_arr.sort();
                    number_arr.sort();
                    string_number_arr.sort();
                    var arr=number_arr.concat(string_arr,string_number_arr);
                    console.log(arr);





                    share|improve this answer












                    var arr=[9,5,'2','ab','3',-1];
                    var string_arr=;
                    var number_arr=;
                    var string_number_arr=;
                    for(var i=0;i<arr.length;i++)
                    {

                    if(typeof(arr[i])=='number')
                    {
                    number_arr.push(arr[i]);

                    }
                    else if((Number(arr[i]).toString())=="NaN")
                    {
                    string_number_arr.push(arr[i]);

                    }
                    else
                    {
                    string_arr.push(arr[i]);
                    }

                    }
                    string_arr.sort();
                    number_arr.sort();
                    string_number_arr.sort();
                    var arr=number_arr.concat(string_arr,string_number_arr);
                    console.log(arr);






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 28 '18 at 12:57









                    PALLAMOLLA SAI

                    974




                    974























                        0














                        You can use Array .sort() method anyway.



                        You just need to provide a function to control sorting criteria for every comparsion.



                        Example:



                        // First of all discretize all kinds of data you want to deal with
                        function typeClassify(v) {
                        return typeof v == "number"
                        ? "N"
                        : isNaN(v) ? "s" : "n"
                        // (Treat all non numeric values as strings)
                        ;
                        };


                        // Second: implement the sorting function
                        function sortCriteria(a, b) {
                        var mode = typeClassify(a) + typeClassify(b);
                        switch (mode) {
                        case "NN":
                        return a - b;
                        case "nn":
                        return Number(a) - Number(b);
                        case "ss":
                        return a == b
                        ? 0
                        : a > b
                        ? -1 : 1
                        ;
                        case "Nn":
                        case "Ns":
                        case "ns":
                        return -1;
                        case "nN":
                        case "sN":
                        case "sn":
                        return 1;
                        default:
                        throw "This must never happen";
                        };
                        };

                        // And finally provide that function as a callback for .sort() method
                        var arr = [9,5,'2','ab','3',-1 ] // to be sorted
                        console.log(arr.sort(sortCriteria));

                        // arr = [-1, 5, 9, "2", "3","ab"] // expected result
                        // arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result


                        Obviously the functionality of typeClassify() function can be flattened into sortCriteria() to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.






                        share|improve this answer




























                          0














                          You can use Array .sort() method anyway.



                          You just need to provide a function to control sorting criteria for every comparsion.



                          Example:



                          // First of all discretize all kinds of data you want to deal with
                          function typeClassify(v) {
                          return typeof v == "number"
                          ? "N"
                          : isNaN(v) ? "s" : "n"
                          // (Treat all non numeric values as strings)
                          ;
                          };


                          // Second: implement the sorting function
                          function sortCriteria(a, b) {
                          var mode = typeClassify(a) + typeClassify(b);
                          switch (mode) {
                          case "NN":
                          return a - b;
                          case "nn":
                          return Number(a) - Number(b);
                          case "ss":
                          return a == b
                          ? 0
                          : a > b
                          ? -1 : 1
                          ;
                          case "Nn":
                          case "Ns":
                          case "ns":
                          return -1;
                          case "nN":
                          case "sN":
                          case "sn":
                          return 1;
                          default:
                          throw "This must never happen";
                          };
                          };

                          // And finally provide that function as a callback for .sort() method
                          var arr = [9,5,'2','ab','3',-1 ] // to be sorted
                          console.log(arr.sort(sortCriteria));

                          // arr = [-1, 5, 9, "2", "3","ab"] // expected result
                          // arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result


                          Obviously the functionality of typeClassify() function can be flattened into sortCriteria() to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.






                          share|improve this answer


























                            0












                            0








                            0






                            You can use Array .sort() method anyway.



                            You just need to provide a function to control sorting criteria for every comparsion.



                            Example:



                            // First of all discretize all kinds of data you want to deal with
                            function typeClassify(v) {
                            return typeof v == "number"
                            ? "N"
                            : isNaN(v) ? "s" : "n"
                            // (Treat all non numeric values as strings)
                            ;
                            };


                            // Second: implement the sorting function
                            function sortCriteria(a, b) {
                            var mode = typeClassify(a) + typeClassify(b);
                            switch (mode) {
                            case "NN":
                            return a - b;
                            case "nn":
                            return Number(a) - Number(b);
                            case "ss":
                            return a == b
                            ? 0
                            : a > b
                            ? -1 : 1
                            ;
                            case "Nn":
                            case "Ns":
                            case "ns":
                            return -1;
                            case "nN":
                            case "sN":
                            case "sn":
                            return 1;
                            default:
                            throw "This must never happen";
                            };
                            };

                            // And finally provide that function as a callback for .sort() method
                            var arr = [9,5,'2','ab','3',-1 ] // to be sorted
                            console.log(arr.sort(sortCriteria));

                            // arr = [-1, 5, 9, "2", "3","ab"] // expected result
                            // arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result


                            Obviously the functionality of typeClassify() function can be flattened into sortCriteria() to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.






                            share|improve this answer














                            You can use Array .sort() method anyway.



                            You just need to provide a function to control sorting criteria for every comparsion.



                            Example:



                            // First of all discretize all kinds of data you want to deal with
                            function typeClassify(v) {
                            return typeof v == "number"
                            ? "N"
                            : isNaN(v) ? "s" : "n"
                            // (Treat all non numeric values as strings)
                            ;
                            };


                            // Second: implement the sorting function
                            function sortCriteria(a, b) {
                            var mode = typeClassify(a) + typeClassify(b);
                            switch (mode) {
                            case "NN":
                            return a - b;
                            case "nn":
                            return Number(a) - Number(b);
                            case "ss":
                            return a == b
                            ? 0
                            : a > b
                            ? -1 : 1
                            ;
                            case "Nn":
                            case "Ns":
                            case "ns":
                            return -1;
                            case "nN":
                            case "sN":
                            case "sn":
                            return 1;
                            default:
                            throw "This must never happen";
                            };
                            };

                            // And finally provide that function as a callback for .sort() method
                            var arr = [9,5,'2','ab','3',-1 ] // to be sorted
                            console.log(arr.sort(sortCriteria));

                            // arr = [-1, 5, 9, "2", "3","ab"] // expected result
                            // arr = [ -1, 5, 9, '2', '3', 'ab' ] // obtained result


                            Obviously the functionality of typeClassify() function can be flattened into sortCriteria() to save a function call on every comparsion. I preferred to put it apart for the sake of clarity.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 28 '18 at 13:00

























                            answered Dec 28 '18 at 12:53









                            bitifet

                            2,298623




                            2,298623






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53958419%2fsort-an-array-which-contains-number-and-strings%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Human spaceflight

                                Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

                                張江高科駅