Okay, at times, we want to make our looping concise, when working with JavaScript arrays. Well, luckily, there is something just for this, JavaScript For Of Loop.
For this guide, we will be looping through a JavaScript array of books, we will call this our library.
To make this more interesting, we will actually let our books have names, so that we can separate the books which begin with vowels, from those that begin with consonants, then we can use their index to know where to retrieve them from in our library!
Let’s start!
Given the below library example:
const libraryOfBooks = [
{
name: "Give and Take: WHY HELPING OTHERS DRIVES OUR SUCCESS",
pages: "260",
},
{
name: "Start Where You Are: A Guide to Compassionate Living",
pages: 242,
},
{
name: "Web Design with HTML and CSS",
pages: 307,
},
{
name: "Android Programming Tutorials",
pages: 447,
},
{
name: "Understanding Automotive Electronics",
pages: 446,
},
];
write a function that will use for of loop to log the below on the console:
{
vowels: [
{ name: 'Android Programming Tutorials', pages: 447, index: 3 },
{
name: 'Understanding Automotive Electronics',
pages: 446,
index: 4
}
],
consonants: [
{
name: 'Give and Take: WHY HELPING OTHERS DRIVES OUR SUCCESS',
pages: '260',
index: 0
},
{
name: 'Start Where You Are: A Guide to Compassionate Living',
pages: 242,
index: 1
},
{ name: 'Web Design with HTML and CSS', pages: 307, index: 2 }
]
}
const librarySorter = (library) => {
const nonCasedVowels = ["a", "e", "i", "o", "u"];
for (const [index, book] of libraryOfBooks.entries()) {
book.index = index;
if (nonCasedVowels.indexOf(book.name.charAt(0).toLowerCase()) !== -1) {
sortedLibrary.vowels.push(book);
} else {
sortedLibrary.consonants.push(book);
}
}
console.log("sortedLibrary", sortedLibrary);
};
Two main things you need to remember from the above solution:
const [index, book]
libraryOfBooks.entries()
We are saying, that we want to get hold of the index and the actual book object. The second value can be of any type, but the index, well, that is what gives us JavaScript for of loop item index, and it is a number.
JavaScript .entries() basically returns us an enumerable version of our array. And in this case, it gives us two things, the index and the item at that index.
And that is it! Simple as that!
Happy coding, until next time, keep doing good and be good!