Javascript Data Type How to - Sort array by number type or String type








Question

We would like to know how to sort array by number type or String type.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from  w ww . ja  v  a 2  s .  c  o m-->
var arr = ['Other', 1, 'Mobile', 27.5, 5];

var nums = arr.filter(function (el) {
    return typeof el === 'number';
}).sort();

document.writeln(nums);
document.writeln('<br/>');


var strings = arr.filter(function (el) {
    return typeof el === 'string';
}).sort();


document.writeln(strings)


</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: