-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtagSearchLab.js
73 lines (67 loc) · 2.07 KB
/
tagSearchLab.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
//lab for searching through an array based on objects and tags.
//Setting up the readline.
const readline = require("readline");
const rli = readline.createInterface(process.stdin, process.stdout);
function ask(questionText) {
return new Promise((res, rej) => {
rli.question(questionText, res);
});
}
//creating results array of objects (surrounded by {}). each has a title and tags property.
let results = [
{
title: "A Wizard of Earthsea",
tags: ["fantasy", "ursula k. le guin"],
},
{
title: "Thing Explainer",
tags: ["science", "technology", "humor", "randal munro"],
},
{
title: "The Fellowship of the Ring",
tags: ["fantasy", "jrr tolkien"],
},
{
title: "A Brief History of Time",
tags: ["history", "science", "stephen hawking"],
},
{
title: "The Great Fairy Tale Tradition",
tags: ["fairy tale", "history", "jack zipes"],
},
{
title: "The Hitchhiker's Guide to the Galaxy",
tags: ["science fiction", "humor", "douglas adams"],
},
{
title: "The Silmarillion",
tags: ["fantasy", "mythology", "jrr tolkien"],
},
{
title: "Eloquent JavaScript",
tags: ["programming", "technology", "marijn haverbeke"],
},
];
//calling function to ask user for a tag.
askingForTag();
//creating a function to ask a user for a tag. passes the tag and calls the filter/search function.
async function askingForTag() {
let userTag = await ask("Please enter a tag!\n");
search(userTag);
}
//creating a function (search) that takes a single argument to return a new array of each book with a matching tag.
function search(userTag) {
userTag = userTag.toLowerCase();
//setting the filter to include any results were the tag includes the user input.
let containsTag = results.filter(function (word) {
return word.tags.includes(userTag);
});
//have to declare empty string or it will say undefined before the first result.
let titleOnly = "";
for (let i = 0; i < containsTag.length; i++) {
titleOnly += containsTag[i].title + "\n";
}
console.log(containsTag);
console.log(titleOnly);
process.exit();
}