function each(coll, func) {
if (Array.isArray(coll)) {
for (var i = 0; i < coll.length; i++) {
func(coll[i], i);
}
} else {
for (var key in coll) {
func(coll[key], key);
}
}
}
Write a function called select that, given an object and an array of
strings representing keys, returns a new object consisting of just the keys
(and values) specified in the array of strings.
function select(object, keys) {
// TODO: your code here
}
select({a: 1, b: 2, c: 3}, ["a", "b"]); // => {a: 1, b: 2}
Write a function called pluck that, given an array of objects as its
first parameter and a string representing a key as its second parameter,
returns an array of all the values found in each object in the array by using
string as a key.
var people = [
{name: {first: "Alyssa", middle: "P.", last: "Hacker"}, age: 26},
{name: {first: "Louis", last: "Reasoner"}, age: 21},
{name: {first: "Ben", last: "Bitdiddle"}, age: 34},
{name: {first: "Eva", middle: "Lu", last: "Ator"}, age: 40},
{name: {first: "Lem", middle: "E.", last: "Tweakit"}, age: 45}
];
function pluck(array, key) {
// TODO: your code here
}
pluck(people, "age"); // => [26, 21, 34, 40, 45]
Write a function called extend that accepts two parameters, a destination
object and a source object. extend should copy all of the keys and values
from the source object (the second parameter) to the destination object
(the first parameter), and return the destination object afterwards. You'll
want to use our new version of each for this.
extend({a: 1, b: 2}, {c: 3, d: 4});
// => {a: 1, b: 2, c: 3, d: 4}
extend({name: "Eva Lu Ator", age: 40}, {name: "Louis Reasoner"});
// => {name: "Louis Reasoner", age: 40}
Complete the below function called zip that takes two arrays as
parameters and combines them to form a single object. The first array
parameter represents the keys of the object, and the second parameter
represents the values (you can assume the two arrays are the same length).
function zip(keys, values) {
// YOUR CODE HERE
}
You should be able to use it like this:
zip(["a", "b", "c"], [1, 2, 3]); // => {a: 1, b: 2, c: 3}
zip(["first", "last"], ["Ben", "Bitdiddle"]); // => {first: "Ben", last: "Bitdiddle"}
zip([], []); // => {}
Write a function deepPluck, where its key parameter can be written in
dot notation -- if the key is written this way, deepPluck will perform a
nested lookup, e.g.
var people = [
{name: {first: "Alyssa", middle: "P.", last: "Hacker"}, age: 26},
{name: {first: "Louis", last: "Reasoner"}, age: 21},
{name: {first: "Ben", last: "Bitdiddle"}, age: 34},
{name: {first: "Eva", middle: "Lu", last: "Ator"}, age: 40},
{name: {first: "Lem", middle: "E.", last: "Tweakit"}, age: 45}
];
function deepPluck(array, key) {
// TODO: your code here
}
pluck(people, "name.first"); // => ["Alyssa", "Louis", "Ben", "Eva", "Lem"]