Theme Layout

Boxed or Wide or Framed

Wide

Theme Translation

Display Featured Slider

Featured Slider Styles

Display Grid Slider

yes

Grid Slider Styles

Display Trending Posts

Display Author Bio

Display Instagram Footer

off

Dark or Light Style

Light

Blog Archive

Powered by Blogger.

Friday, February 17, 2017

[JavaScript] Sorting Arrays


# JavaScript Sorting Arrays


● Sorting an Array

The sort() method sorts an array alphabetically.

● Reversing an Array


The reverse() method reverses the elements in an array.
User can use it to sort an array in descending order.

● Numeric Sort


By default, the sort() function sorts values as strings.
This works well for strings.
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". Because of this, the sort() method will produce incorrect result when sorting numbers. I can fix this by providing a compare function.


Use the same trick to sort an array descending.

● The compare Function


The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments.


When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned value.

● Sorting an Array in Random Order




● Find the Highest ( or Lowest ) Value

 How to find the highest value in an array?


Finding a lowest value is similar as above example.

● Sorting Object Arrays

 JavaScript arrays often contain objects.
Even if objects have properties of different data types, the sort() method can be used to sort the array. The solution is to write a compare function to compare the property values.



QuickEdit
Unknown
1 Comments
Share This Post :

You Might Also Like

1 comment:

Follow @SunriseSunsetBlog