the murmurous sea

JS ES1: sort() 본문

#dev/개념정리

JS ES1: sort()

lunacer 2020. 4. 30. 11:50

1. method 
2. sorts the elements of an array in place and returns the sorted array. 
3. changes the original array.
4. sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
5. By default, the sort() method sorts the values as strings in alphabetical and ascending order.
6. converting the elements into strings, then comparing their sequences of UTF-16 code units values.
7. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
8. produce an incorrect result when sorting numbers.
: when
 numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
: can fix this by providing a "compare function".
  ↳ simply subtract b from a : will sort the array in ascending order (if it doesn't contain Infinity and NaN)

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]

 

[Syntax]

arr.sort([compareFunction])
compareFunction Optional A function that defines an alternative sort order. 
    If omitted, the array elements are converted to strings
    The function should return a negative, zero, or positive value(depending on the arguments).
    When compares two values,
1) it sends the values to the compareFunction
2) sorts the values according to the returned (negative, zero, positive) value.
    e.g. function(a, b){return a-b}

 

[Return Value]

   : The Array object, with the items sorted
   : Note that the array is sorted in place, and no copy is made.


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

https://www.w3schools.com/jsref/jsref_sort.asp

https://www.sitepoint.com/sort-an-array-of-objects-in-javascript/

https://flaviocopes.com/how-to-sort-array-of-objects-by-property-javascript/

'#dev > 개념정리' 카테고리의 다른 글

callback  (0) 2020.05.01
JS ES5: reduce()  (0) 2020.04.30
JS ES5: filter  (0) 2020.04.29
JS ES5: forEach vs map  (0) 2020.04.29
Tree of nodes / DOM  (0) 2020.04.22
Comments