Filter and Sort Methods in JavaScript Arrays
The filter() method generates a new array by evaluating each element of the original array through a callback function. If the callback returns true, the element is included in the new array; otherwise, it's excluded. The original array remains unchanged.
Similar to map(), filter() accepts a function as an argument. However, instead of transforming elements like map(), filter() determines whether to retain or discard each element based on the boolean result of the callback function.
The callback function passed to filter() can recieve up to three parameters:
- The current element being processed in the array.
- The index of the current element.
- The array being traversed (often referred to as
self).
Example 1: Removing even numbers from an array
const numbers = [1, 2, 4, 5, 6, 9, 10, 15];
const oddNumbers = numbers.filter(x => x % 2 !== 0);
console.log(oddNumbers); // [1, 5, 9, 15]
Example 2: Filtering out empty strings
const items = ['A', '', 'B', null, undefined, 'C', ' '];
const validItems = items.filter(s => s && s.trim());
console.log(validItems); // ['A', 'B', 'C']
Example 3: Eliminating duplicates from an array
const duplicates = [7, 6, 5, 214, 5, 9, 7, 80, 3, 6, 45, 48, 46, 24, 26];
const unique = duplicates.filter((value, index, array) => array.indexOf(value) === index);
console.log(unique.toString()); // "7,6,5,214,9,80,3,45,48,46,24,26"
The deduplication logic relies on indexOf() which always returns the index of the first occurrence. Subsequent duplicates have different indices and thus are filtered out.
Sorting with sort()
The sort() method modifies the array in place and returns the sorted array. By default, it converts elements to strings and sorts them lexicographically. For numeric sorting, a comparison function must be provided.
Basic syntax:
array.sort(compareFunction);
Comparison functions:
Ascending order:
const nums = [2, 3, 13, 17, 4, 19, 1];
nums.sort((a, b) => a - b);
console.log(nums); // [1, 2, 3, 4, 13, 17, 19]
Descending order:
const nums = [2, 3, 13, 17, 4, 19, 1];
nums.sort((a, b) => b - a);
console.log(nums); // [19, 17, 13, 4, 3, 2, 1]
Sorting objects by property:
const people = [
{ name: "小明", age: 12 },
{ name: "小红", age: 11 },
{ name: "小刚", age: 15 },
{ name: "小华", age: 13 }
];
const sortByAge = (prop) => (a, b) => a[prop] - b[prop];
people.sort(sortByAge("age"));
console.log(people);
/* Output:
[
{ name: "小红", age: 11 },
{ name: "小明", age: 12 },
{ name: "小华", age: 13 },
{ name: "小刚", age: 15 }
]
*/
Browser Implementation Details
ECMAScript does not mandate a specific sorting algorithm. Different browsers may implement varying approaches. For example, Firefox uses merge sort, whereas Chrome combines insertion sort and quicksort. When the array length is less than or equal to 10, insertion sort is used; otherwise, quicksort is applied for better performance with larger datasets.