阿里云主机折上折
  • 微信号
Current Site:Index > Array sorting and searching

Array sorting and searching

Author:Chuan Chen 阅读数:18181人阅读 分类: JavaScript

Basic Methods for Array Sorting

JavaScript provides several array sorting methods, with the most commonly used being the sort() method. By default, sort() converts elements to strings and sorts them according to Unicode code points:

const fruits = ['banana', 'apple', 'orange', 'grape'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'grape', 'orange']

For sorting numbers, a comparison function is required:

const numbers = [40, 100, 1, 5, 25];
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // [1, 5, 25, 40, 100]

numbers.sort((a, b) => b - a); // Descending order
console.log(numbers); // [100, 40, 25, 5, 1]

Custom Sorting Logic

Comparison functions can handle sorting for complex objects:

const users = [
  { name: 'John', age: 25 },
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 20 }
];

// Sort by age in ascending order
users.sort((a, b) => a.age - b.age);
console.log(users);
// [
//   {name: 'Bob', age: 20},
//   {name: 'John', age: 25},
//   {name: 'Alice', age: 30}
// ]

// Sort by name in alphabetical order
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users);
// [
//   {name: 'Alice', age: 30},
//   {name: 'Bob', age: 20},
//   {name: 'John', age: 25}
// ]

Searching Array Elements

Basic Search Methods

indexOf() and includes() are the simplest search methods:

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 and findIndex Methods

For searching complex objects:

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

Binary Search Implementation

For large sorted arrays, binary search is more efficient:

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

Performance Considerations

Performance differences between search methods in various scenarios:

// Create a large array
const bigArray = Array.from({length: 1000000}, (_, i) => i + 1);

// Test indexOf performance
console.time('indexOf');
bigArray.indexOf(999999);
console.timeEnd('indexOf');

// Test binary search performance
console.time('binarySearch');
binarySearch(bigArray, 999999);
console.timeEnd('binarySearch');

Advanced Search Techniques

Using some and every

Check if any or all elements in an array meet a condition:

const ages = [32, 33, 16, 40];

// Check if at least one element meets the condition
const hasAdult = ages.some(age => age >= 18);
console.log(hasAdult); // true

// Check if all elements meet the condition
const allAdult = ages.every(age => age >= 18);
console.log(allAdult); // false

Filtering Arrays

The filter() method creates a new array based on a condition:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction'];

const longWords = words.filter(word => word.length > 6);
console.log(longWords); // ['exuberant', 'destruction']

Practical Application Examples

Sorting Table Data

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}
// ]

Search Suggestions Implementation

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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.