searching in array
by Ken Sprague
JavaScript
//find matched in arrays
//call method and get a single value
//Array.inclueds( searchElement [, fromIndex]) returns Boolean
//Array.indexOf( searchElement [, fromIndex]) returns -1 or first match
//LOOP and return a single value - provides opportunity for more detailed match
//Array.some( callBack [, fromIndex]) returns Boolean
//Array.find( callBack[, fromIndex]) returns value from Array or undefined
let names = ['Sterling', 'Pam', 'Cyril', 'Lana', 'Mallory', 'Cheryl'];
let log = console.log;
//1. find out if 'Pam' or 'Lana' is in the Array
let bool = names.includes('Pam');
log(bool);
//2. find out what positions in the Array are 'Mallory' or 'Sterling'
let pos = names.indexOf('Taco');
log(pos);
//3. find out whether anyone in the list has a capital letter 'C' in their name
let some = names.some((name)=>{
if(name.indexOf('Q') > -1){
return true;
}
});
log(some);
//4. find the first name in the list that is more than 5 characters plus after 'Sterling'
let find = names.find((name)=>{
if( name.length > 6){
return name;
}
});
log(find);