This is from the challenge at the end of the the "javascript data structures and control" section of stream 1
Created
January 15, 2017 14:00
-
-
Save timmyomahony/fefbefb46dc82908f6970e3f77e42eb8 to your computer and use it in GitHub Desktop.
Javscript data structures and control challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We want to take a paragraph of text and filter out certain parts of it. | |
// In our case, we’ll go over a profile text and remove all the uninteresting stop words. | |
// The steps will involve splitting the text into an array of words. Then iterating over | |
// the words and keeping all words except those that are contained in the separate | |
// array of stop words. You can start by using the following: | |
// | |
// var profile = "I am a web developer developing in html css and javascript"; | |
// var stops = ["i","am","a","and"]; //words to be removed from profile | |
var profile = "I am a web developer developing in html css and javascript"; | |
var stops = ["i","am","a","and"]; | |
// First 'tokenise' the string. This simply means taking the string and breaking | |
// it up into smaller parts (sometimes called "tokens"). We choose what character | |
// we want to split on (called the "delimited"). In our example this is simply a space | |
var words = profile.split(' '); | |
// Approach 1: use a separate array and copy the valid words to it | |
var validWords = [], | |
validProfile = ""; | |
for(i = 0; i < words.length; i++) { | |
// Note: you might try use here: | |
// if(... in ...) | |
// but rememeber the 'in' operator is to check | |
// if a object has a particular key: | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in | |
var word = words[i]; | |
if(stops.indexOf(word.toLowerCase()) === -1) { | |
validWords.push(word); | |
} | |
} | |
// Convert the array back into a string by "joining". This is the opposite of "split". | |
// We stick all the words back together with a space between each of them. | |
validProfile = validWords.join(" "); | |
console.log("Approach 1 result: " + validProfile); | |
// Approach 2: Use the "filter" built in | |
// "filter" is a built-in function available on arrays that allows you to create | |
// new arrays from the original array. You define a function that returns a | |
// boolean value. This function is called on every member of the array. If | |
// the function returns true, that value is included in the result. If it returns | |
// false, it is not included. | |
var validWords = words.filter(function(word) { | |
return (stops.indexOf(word.toLowerCase()) === -1); | |
}); | |
console.log("Approach 2 result: " + validWords); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment