# Array Iterators These are the most commonly used array iterators. We've also provided examples of how and where you might use them. You may want to read the byte on [callback functions](callback-functions.md) first. * [forEach](#forEach) * [map](#map) * [filter](#filter) * [find](#find) * [indexOf](#indexOf) * [reduce](#reduce) * [sort](#sort) # forEach The `.forEach` method iterates over every element in an array and every time it lands on an element it will call the callback function you provide, passing 3 arguments to your callback function's parameters (in order): * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `forEach` `forEach` is great for when you want to iterate over an array and access one element at a time without modifying it's value. ## Example Scenario Imagine a website such as _MailChimp_, where a business can create a mailing list that customers can sign up to. That business might create a new newsletter, which they want to send out to all of their customers. A `forEach` in this scenario might be used to iterate over the mailing list and to call a `sendEmail` function for each email. ### Code ```js const sendEmail = (emailAddress) => { // you don't need to worry about what sendEmail might look like } const emails = [ 'mthurn@live.com', 'rgarcia@optonline.net', 'webdragon@comcast.net', 'crandall@sbcglobal.net', 'fangorn@hotmail.com' ] emails.forEach((email, index) => { console.log('Sending newsletter to ' + email + ' - index ' + index + ' in the list of emails') sendEmail(email) }) ``` ## [forEach on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) # map The `.map` method iterates over each element in an array, calling a callback function you provide. The return value of this function gets appended to a new array (`map` doesn't mutate the original array). 3 arguments get passed to your callback function: * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `map` `map` is great for when you want to create a new array of elements where each element has been calculated from (and corresponds to) an element in a different array. ## Example Scenario A teacher has reports for all of their students. Each report has their name, grade and attendance. Ofsted are inspecting the school and have asked for an anonymised list of grades. We could use a `map` in this scenario to iterate over every `report` in a `reports` array. The callback function we provide will be passed a `report`. We can return `report.grade` from that callback function to create a new array with just grades. ### Code ```js const reports = [{ name: 'Jimmy', grade: 'B', attendance: 96 }, { name: 'Thelma', grade: 'A', attendance: 100 }, { name: 'Aimee', grade: 'C', attendance: 85 }, { name: 'Lee', grade: 'D', attendance: 72 }] const grades = reports.map(report => report.grade) console.log(grades) // ['B', 'A', 'C', 'D'] ``` ## [map on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) # filter The `.filter` method iterates over each element in an array, calling a callback function you provide. If your callback function returns `true` then the current element being iterated over gets added to a new array (`filter` doesn't mutate the original array). 3 arguments get passed to your callback function: * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `filter` `filter` is great for when you want to create a new array of elements (from another array) where all of the elements have met a condition you've set. ## Example Scenario You're shopping for a laptop on eBay, and you're only interested in laptops running Windows XP. You could use `filter`, and pass a callback function that returns `true` if the `currentValue` (current laptop being iterated over) has an `operatingSystem` property with a value of `Windows XP`. ### Code ```js const laptops = [{ model: 'Dell Inspiron', operatingSystem: 'Windows XP', price: 1250 }, { model: 'Microsoft Surface Pro', operatingSystem: 'Windows 10', price: 800 }, { model: 'Lenovo Thinkpad', operatingSystem: 'Ubuntu', price: 250 }, { model: 'Toshiba Satellite', operatingSystem: 'Windows XP', price: 400 }] const windowsXPLaptops = laptops.filter(laptop => { laptop.operatingSystem === 'Windows XP' }) console.log(laptops) // [ // { model: 'Dell Inspiron', operatingSystem: 'Windows XP', price: 1250 }, // { model: 'Toshiba Satellite', operatingSystem: 'Windows XP', price: 400 } // ] ``` ## [filter on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) # find The `.find` method iterates over each element in an array until the callback function you provide returns `true` indicating a record has met criteria you've specified. `find` passes 3 arguments to your callback function's parameters (in order): * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) ## When to use `find` `find` is great when you have a scenario in which you need to retrieve an element from an array and you don't know it's index. ## Example Scenario A local library has books, each of which has an ISBN. Their online e-library system allows members to search for a book by its ISBN and if there is a book (or many books with the same ISBN) then a member can take one out. ### Code ```js const books = [ { name: 'The Wizard of Oz', isbn: '540290' }, { name: 'Pride and Prejudice', isbn: '094290' }, { name: 'Pride and Prejudice', isbn: '094290' }, { name: 'Harry Potter', isbn: '193375' } ] const findBookByIsbn = (isbn, books) => { return books.find(book => book.isbn === isbn) } findBookByIsbn('094290', books) // { name: 'Pride and Prejudice', isbn: '094290' } ``` (Note: there are two Pride and Prejudice books. The one returned will be the one at index 1 as its the first one found) ## [find on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) # indexOf `indexOf` iterates over an array until it finds the given element, at which point it returns the element's index, or `-1` if the element doesn't exist. Unlike other array iterator methods, it doesn't take a callback. It has the following parameters: * `searchElement` - the element you want to find the index for * `fromIndex`- the index to start searching from. Defaults to `0` if not specified. ## When to use `indexOf` Use `indexOf` if you need to find an element's index in order to use other array methods such as [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) (a.k.a deleting an element from an array), or if you want to ensure you don't push a duplicate item into an array. ## Example Scenario Sandra collects coins, but her coin book only has a single slot for each coin. Therefore, if we imagine Sandra's coin book as an array, then we have to ensure Sandra can't _push_ the same coin twice. ### Code ```js const coins = [{ denomination: 50, year: 2012, name: 'Olympic 50p' }, { denomination: 200, year: 2005, name: 'Guy Fawkes £2' }, { denomination: 2, year: 1983, name: 'New Pence Two Pence' }] const addCoin = (coin, coinBook) => { const coinExists = coinBook.indexOf(coin) if (coinExists !== -1) { throw new Error('Coin already exists!') } coinBook.push(coin) } const sandrasCoinBook = [] addCoin(coins[0], sandrasCoinBook) addCoin(coins[0], sandrasCoinBook) // Error: Coin already exists! ``` [find](./find.md) could be used instead in the above scenario. ## Example Scenario Sandra's Mum has found a rare coin that Sandra has been searching for desperately, and rushes over to her house to surprise her. Sandra has already found this coin though. In order to avoid disappointing her Mum, she scrambles over to her coinbook and attempts to find the coin so she can hide it. Given the coin, we need to find it's index so we can _splice_ it from the coinbook. ### Code ```js const coins = [{ denomination: 50, year: 2012, name: 'Olympic 50p' }, { denomination: 200, year: 2005, name: 'Guy Fawkes £2' }, { denomination: 2, year: 1983, name: 'New Pence Two Pence' }] const removeCoin = (coin, coinBook) => { const coinToRemove = coinBook.find(existingCoin => existingCoin.name === coin.name) const existingCoinIndex = coinBook.indexOf(coinToRemove) return coinBook.splice(existingCoinIndex, 1) } const sandrasCoinBook = [{ denomination: 50, year: 2012, name: 'Olympic 50p' }] removeCoin({ denomination: 50, year: 2012, name: 'Olympic 50p' }, sandrasCoinBook) console.log(sandrasCoinBook) // [] ``` We use `find` above because objects are unique. Sandra's 50p and her Mum's 50p are both the same rare specification, but they are different coins. In JavaScript, the object we have as an element in `sandrasCoinBook` is different to the object we pass to `removeCoin`. It is recommended for this reason that if you are working with objects in arrays, that you always use `find` in combination with `indexOf`. ## [indexOf on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) # reduce `reduce` has an accumulator, which - every time an element is iterated over - is modified. When iteration of the array has finished, the `reduce` returns the final value of the accumulator. `reduce` passes 4 arguments to your callback function's parameters (in order): * `accumulator` - the accumulator to modify on each iteration * `currentValue` - the value of the current element * `index` - the index of the current element in the given array * `array` - the array being iterated over (if you've assigned your array to a variable then you usually won't need this parameter) In addition to the callback function, the `reduce` function has a second parameter of `initialValue`. The argument passed is the starting value of `accumulator` (it defaults to the first element in the array otherwise). ## When to use `reduce` The most common use case is when calculating totals, but there are many cool things you can do with `reduce`. Check out [How JavaScript’s Reduce method works, when to use it, and some of the cool things it can do](https://medium.freecodecamp.org/reduce-f47a7da511a9) on Free Code Camp. ## Example Scenario Chelsie has just started University, and needs to budget how much disposable income she'll have left from her maintenance loan a week after expenses. Chelsie's maintenance loan is £200 a week. Note that the example uses pence units, as to prevent any issues that might occur due to decimal precision - read [this article](http://adripofjavascript.com/blog/drips/avoiding-problems-with-decimal-math-in-javascript.html). ### Code ```js const expenses = [{ type: 'rent', amount: 15000 }, { type: 'food', amount: 3000 }, { type: 'books', amount: 1000 }, { type: 'laundry', amount: 500 }, { type: 'travel', amount: 1500 }] const amountRemaining = expenses.reduce((accum, expense) => accum - expense.amount, 20000) console.log(amountRemaining / 100) // -10 ``` ## [reduce on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) # sort `sort` will sort elements in an array. It has an optional parameter of `compareFunction`, which determines the sort order. If `compareFunction` isn't provided, then `sort` will convert all elements in the array to strings and compare them in Unicode point order (uppercase letters come before lowercase letters). The `compareFunction` callback has 2 parameters `a`, and `b`. `a` is the element currently being iterated over, and `b` is the next element in the array. If `compareFunction` returns `0` then their positions in the array will stay the same. If it returns less than `0` then `a` will come before `b`. If it returns greater than `0` then `b` will come before `a`. `sort` mutates the original array. ## When to use `sort` Any scenario in which you need to present data in a particular order, or run a process on data in a particular order. ## Example Scenario On Amazon, the default product sort order is by relevance to the search term. We can use `sort` on an array of products to sort products by lowest price first. ### Code ```js const headphones = [{ name: 'Apple Airpods', price: 15000 }, { name: 'Sony Headphones', price: 5000 }, { name: 'Marshall Headphones', price: 6000 }] headphones.sort((headphonesA, headphonesB) => headphonesA.price - headphonesB.price) console.log(headphones) // [ // { name: 'Sony Headphones', price: 5000 }, // { name: 'Marshall Headphones', price: 6000 } // { name: 'Apple Airpods', price: 15000 }, // ] ``` If `headphonesA` is the object for `Apple Airpods` and `headphonesB` is the object for `Sony Headphones` then the `compareFunction` formula will be `15000 - 5000` which equals `10000`. `10000` is greater than `0` so `headphonesB` gets moved in front of `headphonesA` in the array. ## [sort on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)