Skip to content

Instantly share code, notes, and snippets.

@mikaeelkhalid
Created October 20, 2021 10:27
Show Gist options
  • Save mikaeelkhalid/0be810116751722824b9eb9eb73cc6b2 to your computer and use it in GitHub Desktop.
Save mikaeelkhalid/0be810116751722824b9eb9eb73cc6b2 to your computer and use it in GitHub Desktop.
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 values sequences.

π—³π—Άπ—Ήπ˜π—²π—Ώ()

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.

π—Έπ—²π˜†π˜€()

This method returns a new array iterator that contains the keys for each index in the given input 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]
const array1 = ['x', 'y', 'z'];
const iterator1 = array1.keys();
for (const key of iterator1) {
console.log(key);
} // outputs: 0, 1, 2
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 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment