-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-findindex.js
41 lines (33 loc) · 1.24 KB
/
find-findindex.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
/*
Write a function called `findUserByUsername` which accepts an array of objects, each with a key of username, and a string. The function should return the first object with the key of username that matches the string passed to the function. If the object is not found, return undefined.
const users = [
{username: 'mlewis'},
{username: 'akagen'},
{username: 'msmith'}
];
findUserByUsername(users, 'mlewis') // {username: 'mlewis'}
findUserByUsername(users, 'taco') // undefined
*/
function findUserByUsername(usersArray, username) {
return usersArray.find(function (eachUser) {
return eachUser.username === username;
});
}
/*
Write a function called `removeUser` which accepts an array of objects, each with a key of username, and a string. The function should remove the object from the array. If the object is not found, return undefined.
const users = [
{username: 'mlewis'},
{username: 'akagen'},
{username: 'msmith'}
];
removeUser(users, 'akagen') // {username: 'akagen'}
removeUser(users, 'akagen') // undefined
*/
function removeUser(usersArray, username) {
const idx = usersArray.findIndex(function (eachUser) {
return eachUser.username === username;
});
if (idx !== -1) {
return usersArray.splice(idx,1)[0];
}
}