Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array which contains number and strings

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
like image 369
Komal Bansal Avatar asked Dec 28 '18 12:12

Komal Bansal


People also ask

How do you sort a number in an array of strings?

Using the Arrays.util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is a static method that parses an array as a parameter and does not return anything.

Can we sort String and integer in Java?

String in Java is immutable. There is no direct method to sort a string in Java. You can use Arrays, which has a method CharArray() that will create a char input string and using another method (Arrays.

How do you sort a String of numbers?

Use valueOf() method to convert a String in Java to Short. Let us take a string. String myStr = "5"; Now take Short object and use the valueOf() method.

Does array sort work on strings?

To sort an array of strings in Java, we can use Arrays. sort() function.


Video Answer


2 Answers

The shortest is probably:

 arr.sort((a, b) => ((typeof b === "number") - (typeof a === "number")) || (a > b ? 1 : -1));
like image 61
Jonas Wilms Avatar answered Sep 21 '22 17:09

Jonas Wilms


You can sort the numbers first and then the non-numbers 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 => typeof x != "number").sort(); // Store everything that is not a number in an array (and then sort)

const res = [...nums, ...non_nums]; // combine the two arrays
console.log(res); // [-1, 5, 9, "2", "3", "ab"]
like image 20
Nick Parsons Avatar answered Sep 19 '22 17:09

Nick Parsons