Example of .Map and .IndexOf

Quick and dirty example of using .map and .indexOf to dig into an array for data.

by cwbuecheler

HTML

<a class="userlink" href="#" rel="Bob" title="Choose Bob">Bob</a>

<br />
<a class="userlink" href="#" rel="Sue" title="Choose Sue">Sue</a>

<br />Age: <span id="userAge"></span>

JavaScript

// An Array of Objects
var mainArray = [{
    name: "Bob",
    age: 23
}, {
    name: "Sue",
    age: 28
}];

// Document Ready
$(document).ready(function () {

    // Catch Link Click
    $('a.userlink').on('click', function (e) {

        // Prevent the href from firing
        e.preventDefault();

        // Snag a username from the rel attribute
        var thisUser = $(this).attr('rel');

        // Get the age of that user
        getAge(thisUser);

    });

});

function getAge(user) {

    // Generate an array that only contains the user names
    var justUserNamesArray = mainArray.map(function (arrayItem) {
        return arrayItem.name;
    });

    // Find the index in our generated array of our desired user name
    var indexOfClickedUserName = justUserNamesArray.indexOf(user);

    // Use that number to then get the appropriate user's age
    var userAge = mainArray[indexOfClickedUserName].age;

    // Update the span to show the age
    $('#userAge').text(userAge);

}