-
Notifications
You must be signed in to change notification settings - Fork 0
/
find.js
110 lines (92 loc) · 1.99 KB
/
find.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
///////////////////////
// ES6 - find helper
///////////////////////
/*
var users = [
{ name: 'Jill' },
{ name: 'Alex' },
{ name: 'Bill' },
{ name: 'Alex' }
];
var user;
for (var i = 0; i < users.length; i++) {
if (users[i].name === 'Alex') {
user = users[i];
break;
}
}
console.log(user);
user = users.find(function(user) {
return user.name === 'Alex';
});
console.log(user);
*/
// ============================================
/*
function Car(model) {
this.model = model;
}
var cars = [
new Car('Buick'),
new Car('Camaro'),
new Car('Focus')
];
var findCar = cars.find(function(car) {
return car.model === 'Focus'
});
console.log(findCar);
*/
// ============================================
/*
var posts = [
{ id: 1, title: 'New Post' },
{ id: 2, title: 'Old Post' }
];
var comment = { postId: 1, content: 'Great Post' };
var findPost = function postForComment(posts, comment) {
return posts.find(function(post) {
return post.id === comment.postId;
});
}
console.log(findPost(posts, comment));
*/
// =============================================
/*
// Finding Admin Users
var users = [
{ id: 1, admin: false },
{ id: 2, admin: false },
{ id: 3, admin: true }
];
var admin = users.find(function(user) {
return user.admin;
});
console.log(admin);
*/
// =============================================
// What's Your Balance?
/*
var accounts = [
{ balance: -10 },
{ balance: 12 },
{ balance: 0 }
];
var account = accounts.find(function(account) {
return account.balance === 12;
})
console.log(account);
*/
// =============================================
// Really Challenging: Custom findWhere Helper
var ladders = [
{id: 1, height: 20},
{id: 3, height: 25},
{id: 4, height: 34}
];
function findWhere(array, criteria) {
var property = Object.keys(criteria)[0];
return array.find(function(obj) {
return obj[property] === criteria[property];
});
}
console.log(findWhere(ladders, {height: 34}));