Sort an array which contains number and strings












9














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
    2 hours ago










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    2 hours ago






  • 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
    2 hours ago


















9














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
    2 hours ago










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    2 hours ago






  • 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
    2 hours ago
















9












9








9







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 2 hours ago

























asked 3 hours ago









Komal Bansal

1485




1485












  • 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
    2 hours ago










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    2 hours ago






  • 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
    2 hours ago




















  • 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
    2 hours ago










  • @briosheje because they are strings. Looks like OP wants numbers first, then strings.
    – ksav
    2 hours ago






  • 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
    2 hours ago


















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
2 hours ago




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
2 hours ago












@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
2 hours ago




@briosheje because they are strings. Looks like OP wants numbers first, then strings.
– ksav
2 hours ago




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
2 hours ago






@briosheje "2" and "3" are after 9 because they are strings, So it goes [ints, integer_strings, non_numeric_strings] it seems
– Nick Parsons
2 hours ago














8 Answers
8






active

oldest

votes


















5














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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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



















  • 1




    performance here is bad. Jonas's solution wraps it up with a single sort.
    – Jony-Y
    1 hour ago






  • 2




    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
    40 mins ago





















9














The shortest is probably:



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





share|improve this answer























  • It returns strings first and there's a missing parenthesis at the end
    – Sergio Tx
    1 hour ago












  • @sergio yup, fixed
    – Jonas Wilms
    1 hour ago










  • @JonasWilms beaten me to it :)
    – Jony-Y
    1 hour ago



















1














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














    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
      2 hours ago






    • 3




      @komal a>b returns true or false whereas a number is expected
      – Jonas Wilms
      2 hours ago



















    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
      2 hours ago





















    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
      2 hours ago



















    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









        5














        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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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



















        • 1




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          1 hour ago






        • 2




          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
          40 mins ago


















        5














        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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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



















        • 1




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          1 hour ago






        • 2




          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
          40 mins ago
















        5












        5








        5






        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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 => !nums.includes(x)).sort(); // Store everything not in the numbers array in non_nums 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 2 hours ago

























        answered 2 hours ago









        Nick Parsons

        4,6642721




        4,6642721








        • 1




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          1 hour ago






        • 2




          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
          40 mins ago
















        • 1




          performance here is bad. Jonas's solution wraps it up with a single sort.
          – Jony-Y
          1 hour ago






        • 2




          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
          40 mins ago










        1




        1




        performance here is bad. Jonas's solution wraps it up with a single sort.
        – Jony-Y
        1 hour ago




        performance here is bad. Jonas's solution wraps it up with a single sort.
        – Jony-Y
        1 hour ago




        2




        2




        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
        40 mins ago






        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
        40 mins ago















        9














        The shortest is probably:



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





        share|improve this answer























        • It returns strings first and there's a missing parenthesis at the end
          – Sergio Tx
          1 hour ago












        • @sergio yup, fixed
          – Jonas Wilms
          1 hour ago










        • @JonasWilms beaten me to it :)
          – Jony-Y
          1 hour ago
















        9














        The shortest is probably:



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





        share|improve this answer























        • It returns strings first and there's a missing parenthesis at the end
          – Sergio Tx
          1 hour ago












        • @sergio yup, fixed
          – Jonas Wilms
          1 hour ago










        • @JonasWilms beaten me to it :)
          – Jony-Y
          1 hour ago














        9












        9








        9






        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 1 hour ago

























        answered 2 hours ago









        Jonas Wilms

        54.9k42749




        54.9k42749












        • It returns strings first and there's a missing parenthesis at the end
          – Sergio Tx
          1 hour ago












        • @sergio yup, fixed
          – Jonas Wilms
          1 hour ago










        • @JonasWilms beaten me to it :)
          – Jony-Y
          1 hour ago


















        • It returns strings first and there's a missing parenthesis at the end
          – Sergio Tx
          1 hour ago












        • @sergio yup, fixed
          – Jonas Wilms
          1 hour ago










        • @JonasWilms beaten me to it :)
          – Jony-Y
          1 hour ago
















        It returns strings first and there's a missing parenthesis at the end
        – Sergio Tx
        1 hour ago






        It returns strings first and there's a missing parenthesis at the end
        – Sergio Tx
        1 hour ago














        @sergio yup, fixed
        – Jonas Wilms
        1 hour ago




        @sergio yup, fixed
        – Jonas Wilms
        1 hour ago












        @JonasWilms beaten me to it :)
        – Jony-Y
        1 hour ago




        @JonasWilms beaten me to it :)
        – Jony-Y
        1 hour ago











        1














        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














          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












            1








            1






            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 2 hours ago









            Nurbol Alpysbayev

            3,5971227




            3,5971227























                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
                  2 hours ago






                • 3




                  @komal a>b returns true or false whereas a number is expected
                  – Jonas Wilms
                  2 hours ago
















                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
                  2 hours ago






                • 3




                  @komal a>b returns true or false whereas a number is expected
                  – Jonas Wilms
                  2 hours ago














                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 2 hours ago









                ksav

                4,15721328




                4,15721328












                • 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
                  2 hours ago






                • 3




                  @komal a>b returns true or false whereas a number is expected
                  – Jonas Wilms
                  2 hours ago


















                • 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
                  2 hours ago






                • 3




                  @komal a>b returns true or false whereas a number is expected
                  – Jonas Wilms
                  2 hours ago
















                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
                2 hours ago




                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
                2 hours ago




                3




                3




                @komal a>b returns true or false whereas a number is expected
                – Jonas Wilms
                2 hours ago




                @komal a>b returns true or false whereas a number is expected
                – Jonas Wilms
                2 hours ago











                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
                  2 hours ago


















                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
                  2 hours ago
















                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 2 hours ago

























                answered 2 hours ago









                Jack Bashford

                5,30631234




                5,30631234












                • @NurbolAlpysbayev Fixed now.
                  – Jack Bashford
                  2 hours ago




















                • @NurbolAlpysbayev Fixed now.
                  – Jack Bashford
                  2 hours ago


















                @NurbolAlpysbayev Fixed now.
                – Jack Bashford
                2 hours ago






                @NurbolAlpysbayev Fixed now.
                – Jack Bashford
                2 hours ago













                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
                  2 hours ago
















                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
                  2 hours ago














                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 2 hours ago

























                answered 2 hours ago









                Sergio Tx

                1,6711020




                1,6711020












                • Explanation added with a link to MDN.
                  – Sergio Tx
                  2 hours ago


















                • Explanation added with a link to MDN.
                  – Sergio Tx
                  2 hours ago
















                Explanation added with a link to MDN.
                – Sergio Tx
                2 hours ago




                Explanation added with a link to MDN.
                – Sergio Tx
                2 hours ago











                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 2 hours ago









                    PALLAMOLLA SAI

                    874




                    874























                        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 2 hours ago

























                            answered 2 hours ago









                            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

                                Morgemoulin

                                Scott Moir

                                Souastre