How To Use: sort(), filter() keys() in JavaScript
ππΌπΏπ
This method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings and comparing their UTF-16 code unit value sequences.
const months = [ "Jul", "Aug", "Sep", "Oct", "Mar", "Apr", "May", "Jun", "Nov", "Dec", "Jan", "Feb", ]; months.sort(); console.log(months); // output: [ 'Apr', 'Aug', 'Dec', 'Feb', 'Jan', 'Jul', 'Jun', 'Mar', 'May', 'Nov', 'Oct', 'Sep' ] const numbers = [6, 4, 15, 10, 8]; numbers.sort((a, b) => a - b); console.log(numbers); // output: [ 4, 6, 8, 10, 15 ]
π³πΆπΉππ²πΏ
This method creates a new array with all the elements that pass the test implemented by the provided function. It doesn't execute the function for array elements without values and doesn't change the original array.
const isEven = (num) => num % 2 === 0; const filtered = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].filter(isEven); console.log(filtered); // output: [10, 12, 14, 16, 18, 20]
πΈπ²ππ
This method returns a new array iterator that contains the keys for each index in the given input array.
const array1 = ["x", "y", "z"]; const iterator1 = array1.keys(); for (const key of iterator1) { console.log(key); } // outputs: 0, 1, 2
Quick Recap
How does Array.sort() order elements by default?
By default, sort() converts elements to strings and compares their UTF-16 code unit values in ascending order, which works for strings but produces incorrect results for numbers without a custom comparator.
How do you sort numbers correctly with sort()?
Pass a comparator function, e.g. numbers.sort((a, b) => a - b), so values are compared numerically instead of as strings.
What does Array.filter() return?
A new array containing only the elements that pass the test function you provide, without modifying the original array.
What does Array.keys() return?
An array iterator containing the index keys for each element in the array, e.g. 0, 1, 2 for a three-element array.
Comments
Share your thoughts and questions below