0

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.

3
  • 1
    Use list slicing to move all strings at the end? Commented Apr 14, 2022 at 7:05
  • 1
    Was my answer what you were looking for? Commented Apr 14, 2022 at 7:13
  • I guess that processing will be faster if you keep the standard sort, then detect the strings and move them to the end (or just discard ?). Commented Apr 14, 2022 at 7:55

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for the delay bro, I was testing it, Method 1 was exactly what I wanted, because I wanted to connect it directly to a .map() method, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.