(^150) ❘ CHAPTER 5 ITERATION OF ARRAYS AND OBJECTS
$('ul#rubberSoul').hide();
ul.show();
$(filteredSongs).each(
function()
{
ul.append('
}
);
}
);
The preceding script begins by creating a new array and assigning that array to the variable songs.
The script then selects all
- element with id name rubberSoul and
- element as a new item in the songs array using push(). The end result is
that the songs array contains the titles for all the songs on Rubber Soul.
Then, a new variable is created called filteredSongs, which contains a fi ltered array. The grep()
method is called directly as $.grep(), with the songs array as the fi rst argument and a callback
function as the second argument. In the callback function, you return a boolean value to indicate
whether each item should be kept in the array or removed. Returning true indicates that the value
should be kept; returning false indicates that the item should be discarded. You can also change the
value being kept as well—simply return the replacement value you want to use, and it replaces any
previous value.
In the example, the callback function checks to see if each song title contains the word You, using
JavaScript’s indexOf() method. If it does, the song title is kept; if not, the song title is discarded.
The- element with id name rubberSoul is hidden by selecting it and then making a call to jQue-
- elements to the
- element with id name
rubberSoulFiltered. Figure 5-6 shows the results of the preceding example in a browser.
FIGURE 5-6
ry’s hide() method.
Finally, the script iterates over the new filteredSongs array using each(), and the four song titles
containing the word you are appended as new - elements to the
assigns the text of each