reject
functionfunction reject(array, iteratorFunction) {
// your code here
}
Hint: You may use filter.
Fork this CodePen for some starter code.
Reject should work opposite to filter; if a function returns true
, the item should not be included in the new array, for example:
const numbers = [ 5, 10, 15, 17, 18, 20 ];
const lessThanEighteen = reject(numbers, number => number >= 18);
console.log(lessThanEighteen);
// returns [ 5, 10, 15, 17 ];
reject
functionpluck
functionfunction pluck(array, property) {
// your code here
}
Hint: Access a property on an object by using square bracket notation. For example:
const animal = { type: 'Dinosaur', status: 'Extinct' };
animal['type']; // returns 'Dinosaur'
Pluck should accept an array and a string representing a property name and return an array containing that property from each object, for example:
const cats = [ { name: 'Colonel Meow' }, { name: 'Lil Bub' }, { name: 'Grumpy Cat' }];
pluck(cats, 'name');
// returns ['Colonel Meow', 'Lil Bub', 'Grumpy Cat'];
pluck
functionfindWhere
functionOften we need to find an object with a given property and value. Write a findWhere
function that accepts two parameters, the array and the criteria as an object, and returns the matching object. You may assume that the criteria is one key-value pair. Fork this CodePen for some starter code.
Hint: Use Object.keys(criteria)[0]
to figure out the name of the property on the object. For example, Object.keys({ type: 'marsupial' })
would return 'type'
. You could then check to see if a given element in the array had a property equal to the criteria's value with something like element[property] === criteria[property]
.
The following code ...
const animals = [
{ id: 0, name: 'iguana', type: 'reptile' },
{ id: 1, name: 'cardinal', type: 'bird' },
{ id: 2, name: 'platypus', type: 'marsupial' },
{ id: 3, name: 'frog', type: 'amphibian' }
];
findWhere(animals, { type: 'marsupial' });
would return one object ...
{ id: 2, name: 'platypus', type: 'marsupial' }
filterWhere
functionWrite a filterWhere
function that accepts two parameters, the array and the criteria as an object, and returns an array of matching objects. All of the criteria must match for an object to be included in the resulting array. Assume that multiple criteria can be included, for example:
filterWhere(animals, { name: 'kangaroo', type: 'marsupial' })
Fork this CodePen for some starter code.
Hint: Although you may need different array helpers for this challenge, we recommend warming up with the previous slide's findWhere
challenge first.
The following code ...
const animals = [
{ id: 0, name: 'iguana', type: 'reptile' },
{ id: 1, name: 'cardinal', type: 'bird' },
{ id: 2, name: 'platypus', type: 'marsupial' },
{ id: 3, name: 'kangaroo', type: 'marsupial' },
{ id: 4, name: 'frog', type: 'amphibian' }
];
filterWhere(animals, { type: 'marsupial' });
would return an array of ...
[
{ id: 2, name: 'platypus', type: 'marsupial' },
{ id: 3, name: 'kangaroo', type: 'marsupial' }
]
unique
functionfunction unique(array) {
// your code here
}
Hint: Use reduce and find.
Write a function that will remove duplicate values from an array. For example:
const arr = [ 5, 5, 10, 10, 15, 20, 20 ];
const uniqueArr = unique(arr);
console.log(uniqueArr);
// returns [ 5, 10, 15, 20 ];
unique
functionUsing ES5, we could establish default parameter values, but there were some flaws
View CodePen »
function makeRequest(url, timeout, callback) {
timeout = timeout || 2000; // what if timeout is 0?
callback = callback || function() {};
callback();
}
becomes
function makeRequest(url, timeout, callback) {
timeout = (typeof timeout !== 'undefined') ? timeout : 2000;
callback = (typeof callback !== 'undefined') ? callback || function() {};
callback();
}
function makeRequest(url, timeout = 2000, callback = () => {}) {
callback();
}
It's beautiful
Given the following function:
function makeRequest(url, timeout = 2000, callback = () => {}) {
callback();
}
Only url
is required. The following calls all work:
makeRequest('/api');
makeRequest('/api', 500);
makeRequest('/api', 0, requestData => updateDatabase(requestData));
makeRequest('/api', undefined, requestData => updateDatabase(requestData));
Since default values are only evaluated when used, use it to enforce that a certain parameter is provided:
function mandatory() {
throw new Error('You forgot a parameter!');
}
function doSomething(mustBeProvided = mandatory()) {
return mustBeProvided;
}
See the Pen Default parameters activity by Liz Shaw (@anythingcodes) on CodePen.
Placing ...
before a function parameter transforms that parameter and the rest (i.e. all following parameters) into an array
function giveItARest(param1, ...allTheRest) {
console.log(param1);
console.log(allTheRest);
}
giveItARest(1, 2, 3, 4, 5, 6);
// 1
// [2, 3, 4, 5, 6]
Useful when you don't know how many arguments will be passed to a function
See the Pen Rest parameter activity by Liz Shaw (@anythingcodes) on CodePen.
Placing ...
before an array spreads the array into its individual elements
const numbers = [2, 3, 4];
const numbers = [2, 3, 4];
console.log([1, numbers]);
const numbers = [2, 3, 4];
console.log([1, numbers]); // nested array: [1, [2, 3, 4]]
const numbers = [2, 3, 4];
console.log([1, numbers]); // nested array: [1, [2, 3, 4]]
console.log([1, ...numbers]);
const numbers = [2, 3, 4];
console.log([1, numbers]); // nested array: [1, [2, 3, 4]]
console.log([1, ...numbers]); // normal array: [1, 2, 3, 4]
...
Rest parameters, primarily used in function parameters, to transform individual elements into an array
function sum(first, ...others) {
// others will be an array here
}
Spread operator used on an array to transform the array into individual elements
const arr1 = ['a', 'b', 'c'];
const arr2 = ['x', 'y', 'z'];
const combo = [...arr1, ...arr2];
console.log(combo); // ['a', 'b', 'c', 'x', 'y', 'z']
See the Pen Spread Operator Activity by Liz Shaw (@anythingcodes) on CodePen.
See the Pen Spread and Rest Activity by Liz Shaw (@anythingcodes) on CodePen.
When an object property name is the same as the local variable name, you can include the name without a colon and value
function saveData(url, data){
$.ajax({ method: 'POST', url: url, data: data });
}
becomes
function saveData(url, data){
$.ajax({ url, data, method: 'POST' });
}
Sometimes referred to as enhanced literal notation
Object methods no longer need : function
var dog = {
name: 'Boo',
bark: function() {
console.log('yip!');
}
};
dog.bark(); // yip!
becomes
const dog = {
name: 'Boo',
bark() {
console.log('yip!');
}
};
dog.bark(); // yip!
See the Pen Object Syntax by Liz Shaw (@anythingcodes) on CodePen.
View SolutionUnpack properties from objects into distinct variables
var person = {
name: 'Whitney',
age: 38
};
var name = person.name;
var age = person.age;
console.log(name, age);
// Whitney 38
becomes
const person = {
name: 'Whitney',
age: 38
};
const { name, age } = person;
console.log(name, age);
// Whitney 38
=
){ }
=
)Using Object Destructuring
See the Pen Object Destructuring Activity 1 by Liz Shaw (@anythingcodes) on CodePen.
View SolutionWhat if an object doesn't contain a key with that name?
Set a default value with equal signs (=
)
var person = {
name: 'Whitney'
};
var name = person.name;
var active = person.active; // undefined
console.log(name, active);
// Whitney undefined
becomes
const person = {
name: 'Whitney'
};
const { name, active = false } = person;
console.log(name, active);
// Whitney false
Destructuring is often used in function parameters
const user = {
username: 'TheGreatCatsby',
password: 'catlord',
email: 'catsby@catfancy.com',
dateOfBirth: '04/26/1984',
city: 'Boston'
};
const user = {
username: 'TheGreatCatsby',
password: 'catlord',
email: 'catsby@catfancy.com',
dateOfBirth: '04/26/1984',
city: 'Boston'
};
function register( { email, username, password, dateOfBirth, city }) {
// code to create a new user
}
const user = {
username: 'TheGreatCatsby',
password: 'catlord',
email: 'catsby@catfancy.com',
dateOfBirth: '04/26/1984',
city: 'Boston'
};
function register( { email, username, password, dateOfBirth, city }) {
// code to create a new user
}
register(user); // will be destructured within register() parameters
Using Object Destructuring in Function Parameters
See the Pen Activity: Object Destructuring by Liz Shaw (@anythingcodes) on CodePen.
View SolutionWhat if you want to use a different name for your destructured variables?
const { name, age } = person;
const { name, age } = person;
const localName = name;
// localName is the variable name I want to use going forward
:
in the comma-separated list of keys:
can now be referenced as a local variable
const { name : localName, age } = person;
// now I can reference localName going forward!
Array destructuring operates on positions within an array rather than any named properties
var colors = ['red', 'green', 'blue'];
var first = colors[0];
var second = colors[1];
var third = colors[2];
console.log(first, second, third);
// red green blue
becomes
const colors = ['red', 'green', 'blue'];
const [ first, second, third ] = colors;
console.log(first, second, third);
// red green blue
=
)[]
=
)What if an array doesn't contain a value at that index?
Set a default value with an equal sign (=
)
var scores = [ 94, 89 ];
var first = scores[0];
var second = scores[1];
var third = scores[2] === undefined ? 0 : scores[2];
console.log(first, second, third); // 94 89 0
becomes
const scores = [ 94, 89 ];
const [ first, second, third = 0 ] = scores;
console.log(first, second, third); // 94 89 0
Often you need to swap the values of two variables (especially in sorting algorithms). Use array destructuring to make it happen!
var a = 1;
var b = 2;
var temp = a;
a = b;
b = temp;
console.log(a); // 2
console.log(b); // 1
becomes
let a = 1;
let b = 2;
[ a, b ] = [ b, a ];
console.log(a); // 2
console.log(b); // 1
🌟 No need to create a temporary variable!
Using Array Destructuring
See the Pen Array Destructuring - Converting to Object - Activity by Liz Shaw (@anythingcodes) on CodePen.
detectCollision
functionSee the Pen Class 3 Challenge - detectCollision() by Liz Shaw (@anythingcodes) on CodePen.
detectCollision
works as intended, we can refactor it to improve its performance and readability. Reformat detectCollision
to use destructuring and an array helper.
Hint: We'll return a single matched object. Which array helper would be best in this case?
const node = {
location: {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 4
}
},
range: [0, 3]
};
const {
location: { start },
range: [ index ]
} = node;
console.log(start.line);
console.log(start.column);
console.log(index);
What would the following output to the console and why?