Get help on our basic JavaScript and Algorithms Challenges. If you are posting code that is large use Gist - https://gist.github.com/ paste the link here.
Hi, I'm CamperBot! I can help you in this chatroom :smile:
find TOPIC
find all entries about topic. ex: find js
wiki TOPIC
show contents of topic pagethanks @username
send brownie points to another userabout @username
shows info on that userAlgorithm BONFIRENAME
info on a Algorithm:speech_balloon: meet CamperBot in this room!
andrewaroux sends brownie points to @alpox :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for alpox
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
// Only change code below this line
var secondTree = myPlants.trees[0]; // Change this line
myPlants
is. What type of variable is it?
[
and the ending ]
. So you should first access myPlants
as you would an array.
Can someone tell me what I've done wrong? I get "Type error: this.setFullName is not a function
'''js
var Person = function(firstAndLast) {
var firstName = null;
var lastName = null;
Object.defineProperty(Person.prototype, 'getFirstName', {
get: function() {
return firstName;
}
});
Object.defineProperty(Person.prototype, 'setFirstName', {
set: function(name) {
firstName = name;
}
});
Object.defineProperty(Person.prototype, 'getLastName', {
get: function() {
return lastName;
}
});
Object.defineProperty(Person.prototype, 'setLastName', {
set: function(name) {
lastName = name;
}
});
Object.defineProperty(Person.prototype, 'getFullName', {
get: function() {
return firstName+ ' '+ lastName;
}
});
Object.defineProperty(Person.prototype, 'setFullName', {
set: function(name) {
firstName = name.split(' ')[0];
lastName = name.split(' ')1;
}
});
this.setFullName(firstAndLast);
};
var bob = new Person('Bob Ross');
bob.getLastName();
'''
:bulb: to format code use backticks! ``` more info
var Person = function(firstAndLast) {
var firstName = null;
var lastName = null;
Object.defineProperty(Person.prototype, 'getFirstName', {
get: function() {
return firstName;
}
});
Object.defineProperty(Person.prototype, 'setFirstName', {
set: function(name) {
firstName = name;
}
});
Object.defineProperty(Person.prototype, 'getLastName', {
get: function() {
return lastName;
}
});
Object.defineProperty(Person.prototype, 'setLastName', {
set: function(name) {
lastName = name;
}
});
Object.defineProperty(Person.prototype, 'getFullName', {
get: function() {
return firstName+ ' '+ lastName;
}
});
Object.defineProperty(Person.prototype, 'setFullName', {
set: function(name) {
firstName = name.split(' ')[0];
lastName = name.split(' ')[1];
}
});
this.setFullName(firstAndLast);
};
var bob = new Person('Bob Ross');
bob.getLastName();
zeemax sends brownie points to @alpox :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for alpox
Hi all, trying to figure out how to get the first letter of the array[i] to capitalize it then lower case the remainder, any ideas?
function titleCase(str) {
str.split(" ");
for (i = 0; i < str.length; i++){
}
return str;
}
titleCase("I'm a little tea pot");
james-sangalli sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star: 584 | @khaduch | http://www.freecodecamp.com/khaduch
@johnlovespi You have to get an object of an array with
var p = [ "foo", "bar"]
console.log(p[0]) // Prints "foo"
And access objects like:
var p = {
foo: "bar",
some: "thing"
}
console.log(p.some) // Prints "thing"
Find javascript libraries at http://jster.net
See Also: :loop: Quick JS | :watch: Challenges | :wrench: Exercises | :clipboard: Editors | :newspaper: Blogs | :books: Books
function(input) {
this.foo = yourDefinedFunction(input);
}
Not every class needs to have corresponding CSS. Sometimes we create classes just for the purpose of selecting these elements more easily using jQuery.
For this we use the target
class on the button
elements.
:pencil: read more about challenge create a class to target with jquery selectors on the FCC Wiki
@oglavas It doesnt say it defines functions. It says it defines properties. You just define the getter and the setter of the property as a function.
If you look at how they access the defined property in the example you see:
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
Confused. This waypoint should not be that hard.
"Make Unique Objects by Passing Parameters to our Constructor"
var Car = function(wheels, seats, engines) {
//Change this constructor
this.wheels = 4;
this.seats = 1;
this.engines = 1;
};
//Try it out here
var myCar = new Car(4, 5, 1);
results should be:
Calling new Car(3,1,2) should produce an object with a wheels property of 3, a seats property of 1, and an engines property of 2.
Calling new Car(4,4,2) should produce an object with a wheels property of 4, a seats property of 4, and an engines property of 2.
Calling new Car(2,6,3) should produce an object with a wheels property of 2, a seats property of 6, and an engines property of 3.
myCar should have number values for the wheels, seats, and engines properties.
Mine failed all but the last one. I think I just lost 10 IQ points.
The number beside your picture on Free Code Camp tells you how many Brownie Points you have.
There are three ways you can get Brownie Points:
Brownie Points help you look like the kind of person who codes a lot, shares relevant links, and helps people.
They also add to your Streak.
:pencil: read more about brownie points on the FCC Wiki
caleb272 sends brownie points to @oglavas :sparkles: :thumbsup: :sparkles:
:star: 311 | @oglavas | http://www.freecodecamp.com/oglavas
oglavas sends brownie points to @alpox :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for alpox
var Bike = function() {
// Only change code below this line.
var gear=0;
this.setGear = function(change){
gear=gear+4;
};
this.getGear = function(){
return gear;
};
};
var myCar = new Car();
var myBike = new Bike();
myBike.setGear(change);
Hi guys, can anyone explain to me what the this. operator does. I tried using it for a challenge to set a private variable, but it didn't work. So can someone explain to me the differences of the two following lines of code?
var name = "hello";
this.name = namePassed;
name = namePassed;
Assume all code is inside their appropiate methods and classes.
var Car = function(wheels, seats, engines) {
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
caleb272 sends brownie points to @alpox :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for alpox
@CraigBanach
This is my code:
var Car = function(wheels, seats, engines) {
//Change this constructor
this.wheels = 4;
this.seats = 1;
this.engines = 1;
};
//Try it out here
var myCar = new Car(4, 5, 1);
It still produces an object with 4 wheels, 1 seat and 1 engine, not 5 seats
photogeek1 sends brownie points to @caleb272 and @craigbanach :sparkles: :thumbsup: :sparkles:
:star: 371 | @craigbanach | http://www.freecodecamp.com/craigbanach
:star: 284 | @caleb272 | http://www.freecodecamp.com/caleb272
code-eric sends brownie points to @craigbanach :sparkles: :thumbsup: :sparkles:
:star: 372 | @craigbanach | http://www.freecodecamp.com/craigbanach
@alpox var Bike = function() {
// Only change code below this line.
var gear=0;
this.setGear = function(change){
gear=change+gear;
};
this.getGear = function(){
return gear;
};
};
function searchClicked() {
var searchText = $("#search-bar").val();
var searchQuary = baseurl + "?action=random" + "&format=json";
console.log(searchQuary);
$.ajax({
url: searchQuary,
type: 'GET',
dataType: 'jsonp',
error: function() { alert('Failed!'); },
}).done(function(data) {
console.log(data)
})
}
function queue(arr, item) {
// Your code here
testArr.push(item);
return arr.shift(); // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(queue([5,6,7,8,9], 1)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
@alpox Could you help me in this var Bike = function() {
// Only change code below this line.
var gear = 0;
this.setGear = function(change) {
gear += change;
};
this.getGear = function() {
return gear;
};
}; var myBike = new Bike();
myBike.setGear(4);
=
, not increase it in any way... :blush:
ratishidm sends brownie points to @rphares :sparkles: :thumbsup: :sparkles:
:star: 2947 | @rphares | http://www.freecodecamp.com/rphares
hi all, cant see where I am going wrong on the return the largest number exercise:
function largestOfFour(arr) {
// You can do this!
var largest = 0
//return arr;
for(i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
}
return largest;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
arr[i]
is just your sub-array ([4,5,1,3] .. etc
) you would need one more for loop to check their values
largest
: if ([4,5,1,3] > largest) { etc..
Sorry, can't find a bonfire called making a person. [ Check the map? ]
var Person = function(firstAndLast) {
return firstAndLast;
};
var bob = new Person('Bob Ross');
bob.getFullName();
Fill in the object constructor with the methods specified in the tests.
more info:
bf details
|bf links
|hint
var Person = function(firstAndLast) {
this.setFirstName = (function(first) { this.firstName = first; });
this.setLastName = (function(last) { this.lastName = last; });
this.setFullName = (function(firstAndLast) { var splitMe = firstAndLast.split(" "); this.firstName = splitMe[0]; this.lastName = splitMe[1]; });
this.getFirstName = (function() { return this.firstName;});
this.getLastName = (function() { return this.lastName;});
this.getFullName = (function() { return this.firstName.concat(" ", this.lastName);});
this.setFullName(firstAndLast);
};
var bob = new Person('Bob Ross');
bob.getFullName();
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
myObj.hasOwnProperty("gift"); //true
myObj.hasOwnProperty("pet"); //true
myObj.hasOwnProperty("house"); //false
}
// Test your code by modifying these values
checkObj("gift");
anyone know why i can’t use
var x = lastName.length - 1;
but Instead have to write it like this:
var x = lastName[lastName.length - 1];
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
if (myObj.hasOwnProperty("checkProp")) {
return myObj[checkProp];
} else (myObj.hasOwnProperty) {
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("gift");
"checkProp"
you turned it into a string, when it should be a variable. So remove the quotes. You should also remove (myObj.hasOwnProperty)
in your else
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
if (myObj.hasOwnProperty(checkProp)) {
return myObj[checkProp];
} else (!(checkProp)); {
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("gift");
else
(!(checkProp));
eccentricafterglow sends brownie points to @calicode :sparkles: :thumbsup: :sparkles:
else
is like "do this if any other if
doesn't trigger"
:star: 337 | @calicode | http://www.freecodecamp.com/calicode
default
in a switch
var myObj = {
thePropertyName: "the Value";
};
.
you are directly using the property name itselfvar result = myObj.thePropertyName; // the Value
[]
there are two ways:var result = myObj["thePropertyName"]; // the Value
var prop = "thePropertyName";
var result = myObj[prop]; // the Value
here prop
is the variable that holds the name of your object propertyreza7865 sends brownie points to @davinw :sparkles: :thumbsup: :sparkles:
:star: 211 | @davinw | http://www.freecodecamp.com/davinw
if (check this, and if true) {
// do this
} else if (if the first IF is false, check this too, and if true) {
// do this one instead
} else {
// if none of the if and else if passes, just do this
}
eccentricafterglow sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 709 | @dcnr | http://www.freecodecamp.com/dcnr
dcnr sends brownie points to @eccentricafterglow :sparkles: :thumbsup: :sparkles:
:star: 267 | @eccentricafterglow | http://www.freecodecamp.com/eccentricafterglow
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
var singleVal = array.reduce(function(previousVal, currentVal){
return previousVal + currentVal;
},0);
I don't understand what is happening here.
reduce
's previousVal
is the first index of your array, but if an initial value is set
0
part
previousVal
will be equivalent to your last return
so in this case it would be previousVal + currentVal
@reacorbett
[1, 2, 3, 4]
if initial value is not set:
First iteration:
previousVal = 1
currentVal = 2
return previousVal + currentVal; // 3
Second iteration:
previousVal = 3 // sum of last return
currentVal = 3
return previousVal + currentVal; // 6
Third iteration:
previousVal = 6 // sum of last return
currentVal = 4
return previousVal + currentVal; // 10
The entire array has been processed so
final value is 10
reacorbett sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 710 | @dcnr | http://www.freecodecamp.com/dcnr
var myArr = [["COWS", 10], ["SHEEPS", 20], ["CHICKENS", 30]];
var newObj = myArr.reduce(function(obj, animals) {
var animal = animals[0];
var amount = animals[1];
obj[animal] = amount;
return obj;
}, {}); // initial value is an empty object
// newObj is equivalent to
{
COWS: 10,
SHEEPS: 20,
CHICKENS: 30
}
{}
, obj
(aka our previousval) is now that {}
, and animals
will be the first index in our array which is ["COWS", 10]
and so on!
myArray.reduce(function, initialValue)
{}
is the initial value
obj
instead of previousVal
currentVal
(which I named animals
) would be set to myArr[0]
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
var singleVal = array.reduce(function(previousVal, currentVal){
return previousVal + currentVal;
},0);
singleVal = array;
vsidoren sends brownie points to @reacorbett :sparkles: :thumbsup: :sparkles:
:star: 261 | @reacorbett | http://www.freecodecamp.com/reacorbett
@vsidoren
var singleVal = array.reduce(function(previousVal, currentVal){
return previousVal + currentVal;
},0);
that line of code already defines singleVal as a var and it makes it equal to array.reduce(function(previousVal, currentVal){
return previousVal + currentVal;
function findLongestWord(str) {
var array = str.split(" ");
var longestword = 0;
for (i=0; i < array.length;i++) {
// i know something array[i] > something else
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
bitgrower sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 711 | @dcnr | http://www.freecodecamp.com/dcnr
dcnr sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:star: 632 | @bitgrower | http://www.freecodecamp.com/bitgrower
Definition clarification in Condense Arrays with Reduce
Definition:
To use reduce you pass in a callback whose arguments are an accumulator (in this case, previousVal) and the current value (currentVal).
var singleVal = array.reduce(function(previousVal, currentVal) {
return previousVal - currentVal;
}, 0);
What does accumulator mean? Why are previousVal and currentVal not called parameters?
@dcnr so, you assigned previousVal to "the". and prints to console.
currentVal is assigned the first index of the array. and prints to console
previousVal then is assigned the second index of the array. prints...
the currentVal is = 3rd index , and prints
and all is complete. the new value of new_sentence is assigned, and the last console.log prints.
Is that about it?
var Bike = function() {
// Only change code below this line.
var gear =0;
this.setGear = function(change){
gear += change;
};
this.getGear = function(){
return gear;
};
};
var myCar = new Car();
var myBike = new Bike();
Car
constructor
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
var Bike = function() {
// Only change code below this line.
var gear =0;
this.setGear = function(change){
gear += change;
};
this.getGear = function(){
return gear;
};
};
var myCar = new Car();
var myBike = new Bike();
var Bike = function() {
// Only change code below this line.
var gear;
this.getGear = function() {
return gear;
};
this.setGear = function(change) {
gear = change;
};
};
this.setGear = function(change){
gear += change;
remove + sign
gear
, and you are updating the private variable gear
for each call to setGear
vvang044 sends brownie points to @rsprice and @moigithub :sparkles: :thumbsup: :sparkles:
:star: 355 | @rsprice | http://www.freecodecamp.com/rsprice
:star: 665 | @moigithub | http://www.freecodecamp.com/moigithub
function destroyer(arr) {
function axe(nextNeck) {
for (i = 0; i < arguments.length; i++) {
arguments.indexOf(nextNeck) > 0;
}
}
return arr.filter(nextNeck);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
var array = [1, 12, 21, 2];
array.sort(function(a, b) {
return a - b;
});
so, a,b are the compare function. but, why is return written as a -b ?
arguments
like a normal array, but you'll want to. the first part of arguments
is arr
(in this case [1, 2, 3, 1, 2, 3]
. is this making sense so far?
break;
after the answer = "delta"
function myTest(val) {
var answer = "";
// Only change code below this line
switch (val) {
case 1:
answer = "alpha";
break;
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
}
// Only change code above this line
return answer;
}
// Change this value to test
myTest(1);
This can be a tricky problem to understand. You need to find where in the array a number should be inserted by order, and return the index where it should go.
:pencil: read more about algorithm where do i belong on the FCC Wiki
arr
, you only need to be able to use the parts of arguments
after the first part (index 0). so, make a for loop starting at 1, and push the rest of the arguments into an array that you can use
austinthornley sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 712 | @dcnr | http://www.freecodecamp.com/dcnr
default
case for your switch
```function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return (str.substring(-target.length,target.length) === target);
}
end("Bastian", "n");```
@dcnr
var array = [1, 12, 21, 2];
array.sort(function(a, b) {
return a - b;
});
Why is it return a - b ? i beleive i understand why the compare functions are a and b, but i dont uderstand the return statement.
sort
- If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
- If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
- If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
- compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
a - b
would be ascending, and b - a
would be descending
@rsprice and @qualitymanifest ok, so i tried this:
function destroyer(arr) {
var thePen = [];
for (i=1; i <= arr.length-1; i++) {
if (arr[0].indexOf(i) == -1) {
thePen.push(arr[i]);
}
return thePen;
}
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
...but it doesn't work. arr[0].indexOf(i) is not allowed :/
var code
function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
return (str.substring(-target.length,target.length) === target);
}
end("Bastian", "n");
I'm getting a false when I'm expecting a true. Any ideas why? I tried this on the console and it worke fine. What am I missing?
This an inline `<paste code here>
` code formatting with a single backtick(`) at start and end around the code
.
```js ⇦ Type 3 backticks and then press [shift + enter ⏎]
(type js or html or css)
<paste your code here>,
then press [shift + enter ⏎]
``` ⇦ Type 3 backticks, then press [enter ⏎]
See also: ☛ How to type Backticks | ☯ Compose Mode | ❄ Gitter Formatting Basics
function end(str, target) {
return (str.substring(-target.length,target.length) === target);
}
end("Bastian", "n");
var thePen = arr[0];
substring
is causing your problem btw
' for (var i=0; i < contacts.length; i++) {
if(!contacts[i].hasOwnProperty(prop)) {
return "No such property";
}
if(contacts[i].hasOwnProperty(firstName) && prop==="lastName"){
return contacts[i].lastName;
}
if(contacts[i].hasOwnProperty(firstName) && prop==="likes"){
return contacts[i].likes;
}
else if(!contacts[i].hasOwnProperty(firstName)){
return "No such contact";
}
}'
str = 'Bastian';
str.substring(-str.length, str.length);
"Bastian".substr(-"n".length,"n".length) === "n";
true
```Create a function timesFive that accepts one argument, multiplies it by 5, and returns the new value.
Run tests (ctrl + enter)
dcnr sends brownie points to @reacorbett :sparkles: :thumbsup: :sparkles:
:star: 265 | @reacorbett | http://www.freecodecamp.com/reacorbett
substr
ends up being -1
which should be the last character of your string
// Example
function minusSeven(num) {
return num - 7;
}
// Only change code below this line
function timesFive(num){
return 5*5;
}
function timesFive2(num){
return 5*2;
}
function timesFive0(){
return 0*5;
}
1
which means you'll get one character after the last character... and there aren't any, so you'll just end up getting the last character
andrewaroux sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 713 | @dcnr | http://www.freecodecamp.com/dcnr
str.substr(str.length - 1);
is how I went about it
function end(str, target) {
return str.substr(str.length - 1) === target);
}
function findLongestWord(str) {
var array = str.split(" ");
var longestword = 0;
var total = 0;
for (i=0; i < array.length;i++) {
// i know something array[i] > something else
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
string
subtract one and extract from that index
kiniadit sends brownie points to @rspice :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for rspice
@AndreWaroux for example I always look at http://www.freecodecamp.com/bitgrower 's solutions
Now you're going to embarrass me ... some of my solutions are an unmitigated mess and badly need to be cleaned up ... but there are a couple of gems in there ... SCM is one ... seek & destroy, perhaps -- but the last time I looked at my comments, I still felt they could be way better ...
...and then there's my laziness in not using regexes ...
//iterate over the words in the array
// at each word, compare it to the longest word
// ...?
// profit
I'm just going by the symptom, @JToddFL -- not by looking at the code ...
...this is called "sanity checking" ... because our eyes can fool us!
"The"
is the longest word :)
LOL ... I think there are 3 solutions in there (2 are commented out) ... the first time I created a mini-state machine ...
...I steal profligately ...but I do try to understand what I've stolen, with the goal that I could replicate it if I were faced with the problem again ...
// iterate over each word in the string
// if the current word is longer than the longest word
// set the current word to be the longest word
LARGEST=0
for WORD in [#WORDS ARRAY]
do
if [#WORD > LARGEST]
then
#LARGEST=WORD
fi
end
function myFunction() {
'use strict';
var loc =("myVar");
console.log(loc);
}
console.log(loc);
do
and end
and immediately think Ruby
reacorbett sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 714 | @dcnr | http://www.freecodecamp.com/dcnr
@AndreWaroux -- a state machine is a type of ... uh ... hmmm how do I explain what a state machine is ...
...it does NOT mean something which takes a lot of steps ...
in specific ... I am keeping remembrance of what came in the past, what was my previous "state" -- specifically, was the previous character a blank or not ...
if it was blank, then I did one thing, otherwise I did something else ...
function longest (str) {
// iterate over each word in the string
// if the current word is longer than the longest word
// set the current word to be the longest word
};
We start out with this, which is a perfectly cromulent place to start. We now need to parse our logic and make sure it's sound. We know that iterate means loop, and you very cleverly took care of splitting the array into words, so I'll update our code.
@Code-Eric
Hey guys anyone care to help me ive been stuck in this local variable thing in javascript. Im sure im just overly exhausted and missing something simple. prompt: Declare a local variable myVar inside myFunction
function myFunction() {
'use strict';
console.log(myVar);
}
myFunction();
// run and check the console
// myVar is not defined outside of myFunction
console.log(myVar);
function findLongestWord(str) {
var array = str.split(" ");
var longestword = 0;
var total = 0;
for (i=0; i < array.length;i++) {
total = [index[i] + total
(if total > index[i])
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function longest (str) {
var words = str.split(' ');
// iterate over each word in the string
for (var i = 0; i < words.length; i += 1) {
// if the current word is longer than the longest word
// set the current word to be the longest word
}
};
Look at what we've got now... what's left? We know we're going to have to keep track of the longest string, so that's another variable we'll have to create. Let's update again
:point_up: February 24, 2016 8:46 PM
it looks like bash code to me ...
function longest (str) {
var words = str.split(' ');
var longest = '';
// iterate over each word in the string
for (var i = 0; i < words.length; i += 1) {
// if the current word is longer than the longest word
// set the current word to be the longest word
}
};
Now finally we can see that we need to use some logic to filter out the longest word. A simple if
statement should do just fine. Constructing our if statement is easy now that we have our logic is simple english
```// Example
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
// Setup
var processed = 0;
function process(num) {
return (num + 3) / 5;
}
// Only change code below this line ```
// Example
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
// Setup
var processed = 0;
function process(num) {
return (num + 3) / 5;
}
// Only change code below this line
function longest (str) {
var words = str.split(' ');
var longest = '';
// iterate over each word in the string
for (var i = 0; i < words.length; i += 1) {
var currentWord = words[i];
// if the current word is longer than the longest word
// set the current word to be the longest word
}
};
// Example
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
// Setup
var processed = 0;
function process(num) {
return (num + 3) / 5;
}
// Only change code below this line
reacorbett sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:star: 633 | @bitgrower | http://www.freecodecamp.com/bitgrower
for loop
and try to construct your if
statement based off of that logic
function longest (str) {
var words = str.split(' ');
var longest = '';
// iterate over each word in the string
for (var i = 0; i < words.length; i += 1) {
var currentWord = words[i];
// if the current word is longer than the longest word
// set the current word to be the longest word
}
};
return
the longest
word :)
dcnr sends brownie points to @bitgrower and @reacorbett and @jtoddfl and @rsprice :sparkles: :thumbsup: :sparkles:
:warning: dcnr already gave reacorbett points
:warning: could not find receiver for jtoddfl
:star: 356 | @rsprice | http://www.freecodecamp.com/rsprice
:star: 634 | @bitgrower | http://www.freecodecamp.com/bitgrower
jtoddfl sends brownie points to @rsprice :sparkles: :thumbsup: :sparkles:
:star: 357 | @rsprice | http://www.freecodecamp.com/rsprice
jtoddfl sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:star: 635 | @bitgrower | http://www.freecodecamp.com/bitgrower
function findLongestWord(str) {
var array = str.split(" ");
var longestWord = " ";
var total = 0;
for (i=0; i < array.length;i++) {
var currentWord = array[i];
if (currentWord.length > longestWord.length) {
longestWord = currentWord;
}
}
return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
total
variable?
you also don't need to keep track of the actual word ... just the length ... :)
^^^^ for your consideration ... :)
jtoddfl sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:warning: jtoddfl already gave bitgrower points
Find javascript libraries at http://jster.net
See Also: :loop: Quick JS | :watch: Challenges | :wrench: Exercises | :clipboard: Editors | :newspaper: Blogs | :books: Books
function golfScore(par, strokes) {
// Only change code below this line
if (strokes == 1){
return "Hole-in-one";
}
else if (strokes <= par-2){
return "Eagle";
}
else if (strokes == par-1){
return "Birdie";
}
else if (strokes == par){
return "Par";
}
else if (strokes == par+1){
return "Bogey";
}
else if (strokes == par+2){
return "Double Bogey";
}
else if (strokes >= par+3){
return "Go Home!";
}
// Only change code above this line
}
// Change these values to test
golfScore(5, 4);
This an inline `<paste code here>
` code formatting with a single backtick(`) at start and end around the code
.
```js ⇦ Type 3 backticks and then press [shift + enter ⏎]
(type js or html or css)
<paste your code here>,
then press [shift + enter ⏎]
``` ⇦ Type 3 backticks, then press [enter ⏎]
See also: ☛ How to type Backticks | ☯ Compose Mode | ❄ Gitter Formatting Basics
return
strings closely
cramjet sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star: 1000 | @qualitymanifest | http://www.freecodecamp.com/qualitymanifest
sagit2002 sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 715 | @dcnr | http://www.freecodecamp.com/dcnr
dcnr sends brownie points to @sagit2002 :sparkles: :thumbsup: :sparkles:
:star: 206 | @sagit2002 | http://www.freecodecamp.com/sagit2002
qualitymanifest sends brownie points to @username :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for username
dcnr sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star: 1001 | @qualitymanifest | http://www.freecodecamp.com/qualitymanifest
dcnr sends brownie points to @obama :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for obama
dcnr sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:warning: dcnr already gave bitgrower points
file tax returns
=
in total <= myArr.length
raghuram1994 sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 716 | @dcnr | http://www.freecodecamp.com/dcnr
matiostv sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 717 | @dcnr | http://www.freecodecamp.com/dcnr
No Access-Control-Allow-Origin header is present on the requested resource.
and if I request it as jsonp I get the error Uncaught SyntaxError: Unexpected token :
BUT there is the correct data when I click on the link in the console. How can I get that data to be read correctly?
@Raghuram1994
var myArr = [10, 20, 30];
We access array values via the element's index
var result = myArr[0]; // result would be 10
So we can use a variable to represent the index number too
var index = 1;
var result = myArr[index]; // result would be 20
So we can use use a for
loop to "automate" the incrementing
of the variable we use as index, so we can "go through" the
entire array.
for (var index = 0; index < myArr.length; index++) {
console.log(myArr[index]);
}
Will output:
10
20
30
eagarcia8 sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 718 | @dcnr | http://www.freecodecamp.com/dcnr
eagarcia8 sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:warning: eagarcia8 already gave dcnr points
```function queue(arr, item) {
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(queue(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
```
function queue(arr, item) {
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(queue(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
var oldArray = [1,2,3,4,5,6,7,8,9,10];
// Only change code below this line.
newArray = oldArray.filter(function(val) {
return val < 6;
} );
var newArray = oldArray;
any idea on why the newArray does not return [1, 2, 3, 4, 5]
sudheerswamy sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 719 | @dcnr | http://www.freecodecamp.com/dcnr
var newArray = oldArray;
.filter
part there, but since you made your own, just delete that part var newArray = oldArray;
reacorbett sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 720 | @dcnr | http://www.freecodecamp.com/dcnr
vsidoren sends brownie points to @dcnr :sparkles: :thumbsup: :sparkles:
:star: 721 | @dcnr | http://www.freecodecamp.com/dcnr
var toFilter = [];
for (var i = 1; i < arguments.length; i++){
toFilter.push(arguments[i]);
}
function seekNd(val){
for (var i = 0; i < toFilter.length; i++){
if(val === toFilter[i]){
return false;
}
return true;
}
}
return arr.filter(seekNd);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
var array = [1, 12, 21, 2];
// Only change code below this line.
array.sort(function(a, b) {
return b-a;
});
I passed the challege but confused as to why b-a return a sorted array from largest to smallest
hereshk sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star: 1002 | @qualitymanifest | http://www.freecodecamp.com/qualitymanifest
vsidoren sends brownie points to @vinitm :sparkles: :thumbsup: :sparkles:
:star: 317 | @vinitm | http://www.freecodecamp.com/vinitm
In Computer Science a queue is an abstract Data Structure where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.
Write a function queue which takes an array (arr) and a number (item) as arguments. Add the number to the end of the array, then remove the first element of array. The queue function should then return the element that was removed.
function queue(arr, item) {
// Your code here
queue = [arr, item];
var item = "";
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(queue(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
item
to the back of your array, and remove the first element of your array.
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("dog", "big", "ran", "quickly");
sym
function only accepts a single parameter but there are n
number of arguments being passed. How ? I don't get it.
var strReverse = str.replace(/[^A-Za-z0-9]/g,"").toLowerCase().split('').reverse().join('');
if(str == strReverse) {
return true;
}
return false;
var testArr = [1,2,3,4,5];
console.log(queue(testArr, 6)); // Modify this line to test
testArr
in as the first argument
atryx sends brownie points to @codernoob :sparkles: :thumbsup: :sparkles:
:star: 339 | @codernoob | http://www.freecodecamp.com/codernoob
function queue(arr, item) {
// Your code here
arr = testArr.shift(testArr[0]);
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(queue(testArr, 5)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
arr
, or the array
that you'll be passing in as an argument
arr.shift()
to remove the first element of an array
item
, the thing being passed in to be added to the back of the queue
queue(testArr, 5)
item
, a number, as your second argument
item
and add it to the back of arr
, then you will remove the item from the front of arr
and return it
arr
is being taken in as the whole testArr
and thats the end of the first argument accepted?
arr
represents any array that you pass in to your function
testArray = [1,2,3,4]; queue(testArr, 5)
queue([1,2,3,4], 5)
;
Hi, I'm CamperBot! I can help you in this chatroom :smile:
find TOPIC
find all entries about topic. ex: find js
wiki TOPIC
show contents of topic pagethanks @username
send brownie points to another userabout @username
shows info on that userAlgorithm BONFIRENAME
info on a Algorithm:speech_balloon: meet CamperBot in this room!
find counting
:zero: checkpoint counting cards
find counting
:zero: checkpoint counting cards
reza7865 sends brownie points to @denisdov :sparkles: :thumbsup: :sparkles:
Hi, I'm CamperBot! I can help you in this chatroom :smile:
find TOPIC
find all entries about topic. ex: find js
wiki TOPIC
show contents of topic pagethanks @username
send brownie points to another userabout @username
shows info on that userAlgorithm BONFIRENAME
info on a Algorithm:speech_balloon: meet CamperBot in this room!
:star: 79 | @denisdov | http://www.freecodecamp.com/denisdov
Hi, I'm CamperBot! I can help you in this chatroom :smile:
find TOPIC
find all entries about topic. ex: find js
wiki TOPIC
show contents of topic pagethanks @username
send brownie points to another userabout @username
shows info on that userAlgorithm BONFIRENAME
info on a Algorithm:speech_balloon: meet CamperBot in this room!
You have to go through each word and figure out which one is the longest and return not the word, but how many characters it has.
:pencil: read more about algorithm find the longest word in a string on the FCC Wiki
Hi, I'm CamperBot! I can help you in this chatroom :smile:
find TOPIC
find all entries about topic. ex: find js
wiki TOPIC
show contents of topic pagethanks @username
send brownie points to another userabout @username
shows info on that userAlgorithm BONFIRENAME
info on a Algorithm:speech_balloon: meet CamperBot in this room!
find counting
:zero: checkpoint counting cards
// Setup
function abTest(a, b) {
// Only change code below this line
// Only change code above this line
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
// Change values below to test your code
abTest(2,2);
@codewalker007 if (a < 0 && b < 0){
return undefined;
}
this is not working
if (a < 0 || b < 0){
return "undefined";
}
No Luck
sagit2002 sends brownie points to @kirbyedy :sparkles: :thumbsup: :sparkles:
:star: 535 | @kirbyedy | http://www.freecodecamp.com/kirbyedy
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
if(myObj.hasOwnProperty("checkProp") === true){
return myObj.checkProp;
}else{
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("gift");
.checkProp
looks for property "checkProp". That is the problem there.
function palindrome(str) {
if (str === "") {
return "unknown";
}
var lowerCase = str.toLowerCase();
var noSpaces = lowerCase.replace(/ /g, "");
var splitIt = noSpaces.split("");
if (splitIt === splitIt.reverse) {
return true;
} else if (splitIt !== splitIt.reverse) {
return false;
}
// Good luck!
}
palindrome("racecar");
tmusimbi sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star: 1050 | @masd925 | http://www.freecodecamp.com/masd925
weslez sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star: 1051 | @masd925 | http://www.freecodecamp.com/masd925
var noSpaces = lowerCase.replace(/ /g, "");
/ /g is the regular expression part. http://www.w3schools.com/jsref/jsref_replace.asp explains more
function sumFibs(num) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (var i = 2; i < num; i++){
fib[i] = fib[i-2] + fib[i-1];
}
return fib;
}
sumFibs(4);
myString.replace(/\d/g, "");
photogeek1 sends brownie points to @codewalker007 :sparkles: :thumbsup: :sparkles:
:star: 148 | @codewalker007 | http://www.freecodecamp.com/codewalker007
photogeek1 sends brownie points to @emilaasa :sparkles: :thumbsup: :sparkles:
:star: 294 | @emilaasa | http://www.freecodecamp.com/emilaasa
var str = "Mr Blue has a blue house and a blue car0123456789";
var res = str.replace(/[^A-Za-z0-9]/g, "");
console.log(res);
photogeek1 sends brownie points to @codewalker007 :sparkles: :thumbsup: :sparkles:
:warning: photogeek1 already gave codewalker007 points
urobert sends brownie points to @saintpeter :sparkles: :thumbsup: :sparkles:
:star: 2555 | @saintpeter | http://www.freecodecamp.com/saintpeter
function permGen(n,arr){
var holder=[];
if(n===1){
perms.push(arr);
console.log(arr);
return;
} else {
for(var i=0; i<n-1; i++){
if(n%2===0){
holder=arr[i];
arr[i]=arr[n-1];
arr[n-1]=holder;
permGen(n-1,arr);
} else {
holder=arr[0];
arr[0]=arr[n-1];
arr[n-1]=holder;
permGen(n-1,arr);
}
}
}
return;
}