Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript sort

let arr = [1,2,3,3,4]

arr.sort() => sorts in ascending order from right to left


// You can sort in custom orders by defining a custom comparison function
// ex:

arr.sort(function compareNumbers(firstNumber, secondNumber){
	/*
    if a negative number is returned, firstNumber will be the first number in the output
    if a positive number is returned, secondNumber will be the first number in the output
    if a 0 is returned, it will default to returning them in the position they're already in
    */
  
	// ascending order
  	// return firstNumber - secondNumber
  
    // descending order
    //return secondNumber - firstNumber
  
  	// Always want 3's to come first:
  	/*
  	if firstNumber === 3{
    	return -1
    }
  	if secondNumber === 3{
    	return 1
    }
  	return secondNumber - firstNumber
  	*/
  
  
})



Source by www.quora.com #
 
PREVIOUS NEXT
Tagged: #javascript #sort
ADD COMMENT
Topic
Name
1+5 =