Array Find & FindIndex Methods

Video

JavaScript Notes

JavaScript
    // Array find - looks for first match
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
    // Array findIndex - looks for first match
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
    
    let cities = ["Ankara", "Istanbul", "Antalya", "Bursa", "Trabzon"];
    let city = "Bursa";
    let chars = 7;
    
    let match1 = cities.find(item => {
        if (city === item) return true;
    });
    console.log("item from cities that matched was", match1);
    
    let match2 = cities.find(item => chars === item.length);
    console.log('item with matching length was', match2);
    
    let index = cities.findIndex(
        item => item.toLocaleLowerCase().indexOf("t") > -1
    );
    console.log(`Letter "t" found in item at index ${index}`);
    
    let person = {
        id: 123,
        name: "Recep",
        town: "Istanbul"
    };
    let match3 = cities.find(function (item) {
        if (item === this.town) return true;
    }, person);                                // --> extra argument that represents the object 'this' in the function
                                               // 'this' in arrow functions refers to the lexical scope object
                                               // rather than passed in object - so won't work in this case
    console.log(person.name, "lives in matching town", match3);