0% found this document useful (0 votes)
11 views18 pages

Filtering, Searching and Sorting

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views18 pages

Filtering, Searching and Sorting

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

INFO 2302 Web Technologies

Filtering, searching, and sorting


Dr. Marini Othman
Department of Information Systems
Kulliyyah of Information and Communication Technology
International Islamic University Malaysia
If your pages contain many data,
there are 3 techniques to help your users
find the content they are looking for:-

filtering, searching, and sorting


Filtering Searching Sorting

Allows you to reduce Search is like filtering Sorting lets you


to a set of values. but shows only results reorder a set of items
that match a search on the page based on
Also allows to create term. criteria (for example,
a subset of data that alphabetically).
fulfills a certain
criteria.
INFO 2302 Web Technologies
Filtering
The filter() method

The filter() method of Array instances creates a shallow copy of a


portion of a given array, filtered down to just the elements from the
given array that pass the test implemented by the provided
function.
Simple filtering example

const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const filtered = cats.filter((cat) => cat.startsWith("L"));


console.log(filtered);
// [ "Leopard", "Lion" ]

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


const result = words.filter((word) => word.length > 6);

console.log(result);
// ["exuberant", "destruction", "present"]
Simple filtering example (continued)

const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

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

The search() method of String values executes a search for a match


between a regular expression and this string, returning the index of
the first match in the string.

*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

const str = "hey JudE";


const re = /[A-Z]/;
const reDot = /[.]/;

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

default sort order is according to string Unicode code points.

//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)

//sorting a combination of number and letters


var things = ['word', 'Word', '1 Word', '2 Words’];
things.sort();
// ['1 Word', '2 Words', 'Word', 'word’]
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
Changing order using the compare function

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

Example, consider an array with the values 3, 1, 5, 4, 2.

a should go before b
1 – 3 = -2
a – b = <0

var prices = [3, 1, 5, 4, 2]; //numbers stored in an array


prices.sort(function() { //two values are compared *It is up to the browser to sort in different order.
This example shows the order used by Safari.
return a - b; //decides which goes first Other browsers sort items in different order.
});
//Using a compare function to sort in ascending order
var prices = [1, 2, 125, 2, 19, 14];
prices.sort(function(a,b) {
return a – b;
}

//Using a compare function to sort in descending order


var prices = [1, 2, 125, 2, 19, 14];
prices.sort(function(a,b) {
return b – a;
}
References

MDN Web Docs. Looping codes.


https://developer.mozilla.org/en-
US/docs/Learn/JavaScript/Building_blocks/Looping_code#exiting_loops_with
_break

Duckett. JavaScript and Jquery: interactive front-end web development-


Chapter 12: Filtering, searching and sorting
https://www.javascriptbook.com/code/c12/

You might also like