(ง •̀_•́)ง Ming's blog

Finding and Filtering in JavaScript

References

Content

Other

Math.max

console.log(Math.max(1, 3, 2)); // expected output: 3
console.log(Math.max(-1, -3, -2)); // expected output: -1
var array1 = [1, 3, 2];
console.log(Math.max(...array1)); // expected output: 3

Math.min

console.log(Math.min(2, 3, 1)); // expected output: 1
console.log(Math.min(-2, -3, -1)); // expected output: -3
var array1 = [2, 3, 1];
console.log(Math.min(...array1)); // expected output: 1

String and Array

indexOf

//string
var paragraph =
 "The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
var searchTerm = "dog";
var indexOfFirst = paragraph.indexOf(searchTerm);
console.log('The index of the first "' + searchTerm + '" from the beginning is ' + indexOfFirst);
// expected output: "The index of the first "dog" from the beginning is 40"
console.log(
 'The index of the 2nd "' + searchTerm + '" is ' + paragraph.indexOf(searchTerm, indexOfFirst + 1)
);
// expected output: "The index of the 2nd "dog" is 52"
//array
var beasts = ["ant", "bison", "camel", "duck", "bison"];
console.log(beasts.indexOf("bison")); // expected output: 1
// start from index 2
console.log(beasts.indexOf("bison", 2)); // expected output: 4
console.log(beasts.indexOf("giraffe")); // expected output: -1

lastIndexOf

//string
var paragraph =
 "The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
var searchTerm = "dog";
console.log(
 'The index of the first "' + searchTerm + '" from the end is ' + paragraph.lastIndexOf(searchTerm)
);
// expected output: "The index of the first "dog" from the end is 52"
//array
var animals = ["Dodo", "Tiger", "Penguin", "Dodo"];
console.log(animals.lastIndexOf("Dodo"));
// expected output: 3
console.log(animals.lastIndexOf("Tiger"));
// expected output: 1

String

var paragraph =
 "The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
// any character that is not a word character or whitespace
var regex = /[^\w\s]/g;
console.log(paragraph.search(regex)); // expected output: 43
console.log(paragraph[paragraph.search(regex)]); // expected output: "."

match

var paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
var regex = /[A-Z]/g;
var found = paragraph.match(regex);
console.log(found); // expected output: Array ["T", "I"]

Array

findIndex

var array1 = [5, 12, 8, 130, 44];
function isLargeNumber(element) {
 return element > 13;
}
console.log(array1.findIndex(isLargeNumber)); // expected output: 3

find

var array1 = [5, 12, 8, 130, 44];
var found = array1.find(function(element) {
 return element > 10;
});
console.log(found);
// expected output: 12

filter

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
const result = words.filter(word => word.length > 6);
console.log(result); // expected output: Array ["exuberant", "destruction", "present"]