Table of Contents
Sorting and filtering data in arrays and lists are common tasks in programming and data management. These methods help organize data for easier analysis and retrieval. This article provides practical examples and calculations to demonstrate effective techniques for sorting and filtering.
Sorting Data in Arrays
Sorting involves arranging data in a specific order, such as ascending or descending. Many programming languages offer built-in functions to perform sorting efficiently.
For example, in JavaScript, the sort() method sorts an array alphabetically or numerically. To sort numbers in ascending order:
Example:
const numbers = [5, 2, 9, 1];
numbers.sort((a, b) => a - b);
Result: [1, 2, 5, 9]
Filtering Data in Lists
Filtering selects data that meets specific criteria. This process reduces the dataset to relevant items.
In JavaScript, the filter() method creates a new array with elements that pass a test.
Example:
const ages = [12, 17, 20, 25, 30];
const adults = ages.filter(age => age >= 18);
Result: [20, 25, 30]
Combining Sorting and Filtering
Sorting and filtering can be combined to refine data sets further. First, filter the data, then sort the filtered results.
For example, filtering a list of products by price and then sorting by name:
Example:
const products = [
{ name: 'Apple', price: 3 },
{ name: 'Banana', price: 1 },
{ name: 'Cherry', price: 5 }
];
const affordableProducts = products.filter(p => p.price <= 3);
affordableProducts.sort((a, b) => a.name.localeCompare(b.name));
Result: [{ name: ‘Apple’, price: 3 }, { name: ‘Banana’, price: 1 }]