Q:

string sort javascript

var string='ACBacb';
var sortedString = string.split('').sort().join('');
2
if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;
1
arr = ['width', 'score', done', 'neither' ]
arr.sort() // results to ["done", "neither", "score", "width"]

arr.sort((a,b) => a.localeCompare(b)) 
// if a-b (based on their unicode values) produces a negative value, 
// a comes before b, the reverse if positive, and as is if zero

//When you sort an array with .sort(), it assumes that you are sorting strings
//. When sorting numbers, the default behavior will not sort them properly.
arr = [21, 7, 5.6, 102, 79]
arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
// b - a will give you the reverse order of the sorted items 

//this explnation in not mine
1
//sorts arrays of numbers
function myFunction() {
  points.sort(function(a, b){return a-b});
  document.getElementById("demo").innerHTML = points;
}
2
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
1
var names = ["Peter", "Emma", "Jack", "Mia"];
var sorted = names.sort(); // ["Emma", "Jack", "Mia", "Peter"]
0

New to Communities?

Join the community