Iterators Flashcards
How could we change the contents of an array? What iterator method can you use? We can also use a return statement. (Give example and then log the array to the console while putting it into a string)
You can use the .map() method, like so:
let secretMessage = animals.map(word => words[0]); console.log(secretMessage.join(' '))
This will print out the first letter of each word in the animals array
There is another method like .map() that can return a new array. However, there is one method that can return certain elements from the original array that evaluate to truth based on conditions written in the block of the method. What method is this and write an example using it.
let smallNumbers = bigNumbers.filter(number => number < 250); console.log(smallNumbers);
Choose the right Iterator method for each of these scenarios (Replace the word method)
let cities = [‘Nashville’, ‘Charlotte’, ‘Asheville’, ‘Austin’, ‘Boulder’];
let nums = [1, 50, 75, 200, 350, 525, 1000];
// Choose a method that will return undefined cities.method(city => console.log('Have you visited ' + city + '?'));
// Choose a method that will return a new array let longCities = cities.method(city => city.length > 7);
// Choose a method that will return a new array let smallerNums = nums.method(num => num - 5);
// Choose a method that will return a boolean value nums.method(num => num < 0);
let cities = [‘Nashville’, ‘Charlotte’, ‘Asheville’, ‘Austin’, ‘Boulder’];
let nums = [1, 50, 75, 200, 350, 525, 1000];
// Choose a method that will return undefined cities.forEach(city => console.log('Have you visited ' + city + '?'));
// Choose a method that will return a new array let longCities = cities.filter(city => city.length > 7);
// Choose a method that will return a new array let smallerNums = nums.map(num => num - 5);
// Choose a method that will return a boolean value nums.every(num => num < 0);
If you have the following variable that has a string value: var string = 'scott18'; How would you return only the numbers?
var string = 'scott18'; var numConversion = string.split('').map(item => parseInt(item)); var numFilter = numConversion.filter(item => !isNaN(item));
Create a function which takes a string as an argument and returns the longest word from the string.
function longestWord(sen) { sen = sen.split(' '); sen.sort(function(a,b) { return b.length-a.length; }); return sen.slice(0,1).join(''); }
With the following array, organise the numbers to be smallest to biggest:
arr = [2, 10, 5];
arr.sort(function(a,b) {
return a-b;
})