Iterators Flashcards

1
Q

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)

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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.

A
let smallNumbers = bigNumbers.filter(number => number < 250);
console.log(smallNumbers);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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);
A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
If you have the following variable that has a string value: var string = 'scott18';
How would you return only the numbers?
A
var string = 'scott18';
var numConversion = string.split('').map(item => parseInt(item));
var numFilter = numConversion.filter(item => !isNaN(item));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Create a function which takes a string as an argument and returns the longest word from the string.

A
function longestWord(sen) {
sen = sen.split(' ');
sen.sort(function(a,b) {
return b.length-a.length;
});
return sen.slice(0,1).join('');
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

With the following array, organise the numbers to be smallest to biggest:

arr = [2, 10, 5];

A

arr.sort(function(a,b) {
return a-b;
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly