数组排序与搜索
数组排序的基本方法
JavaScript提供了多种数组排序方法,最常用的是sort()
方法。默认情况下,sort()
会将元素转换为字符串后按Unicode码点排序:
const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']
对于数字排序,需要提供比较函数:
const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b); // 升序
console.log(numbers); // [1, 5, 25, 40, 100]
numbers.sort((a, b) => b - a); // 降序
console.log(numbers); // [100, 40, 25, 5, 1]
自定义排序逻辑
比较函数可以处理复杂对象的排序:
const users = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 20 }
];
// 按年龄升序
users.sort((a, b) => a.age - b.age);
console.log(users);
// [
// {name: 'Bob', age: 20},
// {name: 'John', age: 25},
// {name: 'Alice', age: 30}
// ]
// 按名字字母顺序
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users);
// [
// {name: 'Alice', age: 30},
// {name: 'Bob', age: 20},
// {name: 'John', age: 25}
// ]
搜索数组元素
基本搜索方法
indexOf()
和includes()
是最简单的搜索方法:
const colors = ['red', 'green', 'blue', 'yellow'];
console.log(colors.indexOf('blue')); // 2
console.log(colors.indexOf('purple')); // -1
console.log(colors.includes('green')); // true
find和findIndex方法
对于复杂对象的搜索:
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find(item => item.name === 'cherries');
console.log(result); // {name: 'cherries', quantity: 5}
const index = inventory.findIndex(item => item.quantity === 0);
console.log(index); // 1
二分搜索实现
对于已排序的大数组,二分搜索效率更高:
function binarySearch(sortedArray, target) {
let left = 0;
let right = sortedArray.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (sortedArray[mid] === target) {
return mid;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
const sortedNumbers = [1, 3, 5, 7, 9, 11, 13, 15];
console.log(binarySearch(sortedNumbers, 9)); // 4
console.log(binarySearch(sortedNumbers, 10)); // -1
性能考虑
不同搜索方法在不同场景下的性能差异:
// 创建一个大数组
const bigArray = Array.from({length: 1000000}, (_, i) => i + 1);
// 测试indexOf性能
console.time('indexOf');
bigArray.indexOf(999999);
console.timeEnd('indexOf');
// 测试二分搜索性能
console.time('binarySearch');
binarySearch(bigArray, 999999);
console.timeEnd('binarySearch');
高级搜索技巧
使用some和every
检查数组中是否存在或所有元素满足条件:
const ages = [32, 33, 16, 40];
// 检查是否有至少一个元素满足条件
const hasAdult = ages.some(age => age >= 18);
console.log(hasAdult); // true
// 检查所有元素是否满足条件
const allAdult = ages.every(age => age >= 18);
console.log(allAdult); // false
过滤数组
filter()
方法可以基于条件创建新数组:
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction'];
const longWords = words.filter(word => word.length > 6);
console.log(longWords); // ['exuberant', 'destruction']
实际应用示例
表格数据排序
const tableData = [
{ id: 1, name: 'Product A', price: 99.99, stock: 10 },
{ id: 2, name: 'Product B', price: 49.99, stock: 25 },
{ id: 3, name: 'Product C', price: 149.99, stock: 5 }
];
function sortTable(property, direction = 'asc') {
return [...tableData].sort((a, b) => {
if (a[property] < b[property]) return direction === 'asc' ? -1 : 1;
if (a[property] > b[property]) return direction === 'asc' ? 1 : -1;
return 0;
});
}
console.log(sortTable('price', 'desc'));
// [
// {id: 3, name: 'Product C', price: 149.99, stock: 5},
// {id: 1, name: 'Product A', price: 99.99, stock: 10},
// {id: 2, name: 'Product B', price: 49.99, stock: 25}
// ]
搜索建议实现
const searchSuggestions = [
'apple', 'banana', 'cherry', 'date', 'elderberry',
'fig', 'grape', 'honeydew', 'kiwi', 'lemon'
];
function getSuggestions(input) {
if (!input) return [];
return searchSuggestions.filter(item =>
item.toLowerCase().includes(input.toLowerCase())
).slice(0, 5);
}
console.log(getSuggestions('a')); // ['apple', 'banana', 'date', 'grape', 'honeydew']
console.log(getSuggestions('ap')); // ['apple', 'grape']
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn