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

Time:04-14

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:

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.

CodePudding user response:

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));
  • Related