Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
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:

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!