Finding Matches in Arrays

Video

JavaScript Notes

JavaScript
    // Array.prototype.indexOf()   //returns index number
    // Array.prototype.contains()  //returns boolean
    // Array.prototype.filter()    //returns array
    // Array.prototype.some()      //returns boolean
    // Finding matches in Arrays
    
    const log = console.log;
    
    let names = ['Archer', 'Lana', 'Cyril', 'Pam', 'Cheryl'];
    
    let pos = names.indexOf('Pam');
    //log( pos, names[pos] );
    
    //remove the element
    names.splice(pos, 1);
    //log(names);
    
    let movies = [
        {id:1, title:'Shaun of the Dead'},
        {id:2, title:'Man Up'},
        {id:3, title:'Terminal'},
        {id:4, title:'The End of the World'},
        {id:5, title:'Hot Fuzz'},
        {id:6, title:'Mission Impossible: Fallout'}
    ]
    
    let manUp = {id:2, title:'Man Up'};
    pos = movies.indexOf(manUp);
    log('Man Up in position', pos);    // this returns -1, no match found
    
    // Array.filter - loops through all elements of the Array. Doesn't stop when match is found
    let iterations = 0;
    
    let matchingMovie = movies.filter( (obj) => {
        iterations++;
        if(obj.id === manUp.id){
            return true;
        }
        return false;
    })
    log( matchingMovie[0], 'after looping', iterations );     // iterations will be Array.Length!
    
    // Array.some - loops through elements of the Array, and stops when match is found
    iterations=0;
    
    let found = movies.some( (obj, index) => {
        iterations++;
        if(obj.id === manUp.id){
            pos = index;
            return true;
        }
        return false;
    })
    //log( found.toString(), 'after looping', iterations);    // iterations will be << Array.Length!
    log( movies[pos], 'after looping', iterations);