Filtering, Searching and Sorting
Filtering, Searching and Sorting
console.log(result);
// ["exuberant", "destruction", "present"]
Simple filtering example (continued)
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
console.log(array.filter(isPrime));
// [2, 3, 5, 7, 11, 13]
INFO 2302 Web Technologies
Searching
The search() method
*Refer https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet
for the MDN Regular expressions cheatsheet
Simple searching example using regular expressions
console.log(str.search(re));
// returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot));
// returns -1 cannot find '.' dot punctuation
const para = document.querySelector('p');
Simple contact search const input = document.querySelector('input');
const btn = document.querySelector('button');
example
btn.addEventListener('click', () => {
<!DOCTYPE html> const searchName = input.value.toLowerCase();
<html lang="en-US"> input.value = '';
<head> input.focus();
<meta charset="utf-8"> para.textContent = '';
<meta name="viewport" content="width=device-width"> for (let contact of contacts) {
<title>Simple contact search example</title> let splitContact = contact.split(':');
</head> if (splitContact[0].toLowerCase() === searchName) {
<body> para.textContent = splitContact[0] + '\'s number is ' +
splitContact[1] + '.';
<label for="search">Search by contact name: </label> break;
<input id="search" type="text"> }
<button>Search</button> }
if (para.textContent === '') {
<p></p> para.textContent = 'Contact not found.';
}
<script> });
const contacts = ['Chris:2232322',
'Sarah:3453456', </script>
'Bill:7654322', </body>
'Mary:9998769', </html>
'Dianne:9384975'];
INFO 2302 Web Technologies
Sorting
The sort() method
The sort() method sorts the elements of an array in place and returns the array. The
//sorting strings
var fruit = ['cherries', 'apples', 'bananas’];
fruit.sort();
// ['apples', 'bananas', 'cherries’]
//sorting numbers
var scores = [1, 10, 21, 2];
scores.sort();
// [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
The sort() method (continued)
The sort () method only ever compares two values at a time (you will see
these referred to as a and b), and it determines whether value a should
appear before or after value b.
If you want to change the order of the sort, you write a compare function.
A compare function should return a number. That number indicates which
of the items should come first.
If compare function returns,
• <0, indicates that it should show a before b
• 0, indicates that the items should remain in the same
order
• >0, indicates that it should show b before a
a should go before b
1 – 3 = -2
a – b = <0