How To Use: sort(), filter() keys() in JavaScript

Β·

1 min read

Play this article

π˜€π—Όπ—Ώπ˜()

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
Β