Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting an Array that consists of numbers, BUT can include strings

I am facing an issue where I get results from API(mainly array of numbers), but if the devs make mistake and leave the field empty I will get empty string ("").
I am trying to sort this array in an ascending order and move the empty strings in the back of the Array, like that:

let arr = [3, 4, "", 1, 5, 2]   // Example Array from api

This array, when modified should become:

let res = [1, 2, 3, 4, 5, ""]

I tried using the arr.sort() method, but the results look like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let res = ["",1 ,2 ,3 ,4 ,5]

For some reason when the element is string, the sort method puts it in the front, not in the end like it does with undefined or null for example.

>Solution :

Method 1

let arr = [3, 4, "", 1, 5, 2];
const res = arr.sort((a, b) => {
    if (typeof a === 'string') {
        return 1;
    } else if (typeof b === 'string') {
        return -1;
    } else {
        return a - b;
    }
}
);

console.log(res)

Output:

[ 1, 2, 3, 4, 5, '' ]

Method 2

const res = (arr) => {
    let newArr = [];
    let strArr = [];
    for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === 'string') {
            strArr.push(arr[i]);
        } else {
            newArr.push(arr[i]);
        }
    }
    return newArr.concat(strArr);
}

console.log(res(arr));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading