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.
function updateRecords(id, prop, value) {
if (value !== "") {
if (collection[id].prop !== "tracks") {
collection[id].prop = value;
console.log("Not tracks!");
}
else if (collection[id].prop == "tracks") {
collection[id].prop.push(value);
}
else if (collection.hasOwnProperty[id].prop === false) {
collection[id].prop = value;
}
else {
delete collection[id].prop;
}
}
return collection;
}
hitmikey sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:warning: hitmikey already gave chrono79 points
@hitmikey rethink this block
else if (collection[id].prop == "tracks") {
collection[id].prop.push(value);
}
else if (collection.hasOwnProperty[id].prop === false) {
collection[id].prop = value;
}
If "tracks" is non-existent before you update it, create an empty array before pushing a track to it.
You know how you can put
if (foo === false) -> if (!foo)
if (foo===true) -> if (foo)
if you put
if (maybeTrueOrFalse)
will it evaluate the true or false?
in my example I have
function dropElements(arr, func) {
for (var i = 0; i < arr.length; i++) {
if (func(arr[i])) { //<—— on this line will this execute this line if func(arr[i]) is false or only when it is true?
return arr;
} arr.shift()
}
}
if (func(arr[i])
does
if (func(arr[i])
the same thing as
if (func(arr[i]) === true)
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=6;//private
this.setGear = function(){
myBike.setGear = 4;
};
this.getGear = function(){
return this.setGear;
};
};
//console.log(setGear);
var myCar = new Car();
var myBike = new Bike();
@jesusdaver86 setGear needs a param and you have to change the value of gear inside it
this is also wrong:
this.getGear = function(){
return this.setGear;
};
check the code example above
var count = 0;
function cc(card) {
// Only change code below this line
var answer = "";
switch(card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count += 1;
answer = count + " Bet";
break;
}
if (card > 7 && card <10) {
answer = count + " Hold";
}
switch(card) {
case 10:
case "J":
case "Q":
case "K":
case "A":
count += -1;
answer = count + " Hold";
break;
}
return answer;
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
jesusdaver86 sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1199 | @chrono79 |http://www.freecodecamp.com/chrono79
@umairbalani
if (card > 7 && card <10) {
answer = count + " Hold";
}
this isn't right, in fact none of the answer assignations should be inside card evaluations
function dropElements(arr, func) {
for (var i = 0; i < arr.length; i++) {
if (!func(arr[i])) {
arr.shift()
}
} return arr;
}
@Vanhealen reread the instructions:
Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.
The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not.
Return the rest of the array, otherwise return an empty array.
else if (collection[id][prop] == "tracks") {
collection[id][prop].push(value);
}
function dropElements(arr, func) {
for (var i = 0; i < arr.length; i++) {
if (!func(arr[i])) {
arr.shift()
i--
}
} return arr;
}
if (collection[id][prop] == "tracks") {
if ... {
collection[id][prop] = [];
}
// here you can use push safely
awbunys sends brownie points to @magnesium-mike :sparkles: :thumbsup: :sparkles:
:cookie: 350 | @magnesium-mike |http://www.freecodecamp.com/magnesium-mike
anacou sends brownie points to @awbunys :sparkles: :thumbsup: :sparkles:
:cookie: 174 | @awbunys |http://www.freecodecamp.com/awbunys
function updateRecords(id, prop, value) {
if (value !== "") {
if (collection[id][prop] !== "tracks") {
collection[id][prop] = value;
}
else if (collection[id][prop] == "tracks") {
if (collection.hasOwnProperty[id][prop][value] === false) {
collection[id][prop][value] = [ ];
}
collection[id][prop][value].push();
}
}
else {
delete collection[id][prop][value];
}
return collection;
}
collection[id][prop][value]
to this collection[id][prop]
push();
to this push(value);
collection.hasOwnProperty[id][prop][value]
to this collection[id].hasOwnProperty(prop)
function updateRecords(id, prop, value) {
if (value !== "") {
if (collection[id][prop] !== "tracks") {
collection[id][prop] = value;
}
else if (collection[id][prop] == "tracks") {
if (collection.hasOwnProperty(prop) === false) {
collection[id][prop][value] = [ ];
}
collection[id][prop].push(value);
}
}
else {
delete collection[id][prop];
}
return collection;
}
hitmikey sends brownie points to @hrokr :sparkles: :thumbsup: :sparkles:
:cookie: 267 | @hrokr |http://www.freecodecamp.com/hrokr
if (collection.hasOwnProperty(prop) === false) {
collection[id][prop][value] = [ ];
function updateRecords(id, prop, value) {
if (value !== "") {
if (collection[id][prop] !== "tracks") {
collection[id][prop] = value;
}
else if (collection[id][prop] == "tracks") {
if (collection[id].hasOwnProperty(prop) === false) {
collection[id][prop] = [ ];
}
collection[id][prop].push(value);
}
}
else {
delete collection[id][prop];
}
return collection;
}
var result = arr.push(item);
result =arr.shift();
return result;
@Vanhealen If you read the documentation carefully you would see that you do not need a loop to do this
collection.hasOwnProperty(prop) === false) {
```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 ⏎]
This an inline `<paste code here>
` code formatting with a single backtick() at _start_ and _end_ around the
code`.
See also: ☛ How to type Backticks | ☯ Compose Mode | ❄ Gitter Formatting Basics
var oldArray = [1, 2, 3, 4, 5];
var newArray = oldArray.map(function(num) {
return num + 3;
});
function reverseString(str) {
var i = str;
var s = i.split("");
var r = s.reverse();
var j = r.join('');
return j;
}
reverseString(["hello"]);
reverseString("hello");
(no brackets in function call)
arsalansavand sends brownie points to @eeflores :sparkles: :thumbsup: :sparkles:
:cookie: 753 | @eeflores |http://www.freecodecamp.com/eeflores
My code:
function updateRecords(id, prop, value) {
if (value !== "") {
if (collection[id][prop] !== "tracks") {
collection[id][prop] = value;
}
else if (collection[id][prop] == "tracks") {
if (collection[id].hasOwnProperty(prop) === false) {
collection[id][prop] = [ ];
}
collection[id][prop].push(value);
}
}
else {
delete collection[id][prop];
}
return collection;
}
Solution:
function updateRecords(id, prop, value) {
if (prop === "tracks" && value !== "") {
if(collection[id][prop]){
collection[id][prop].push(value);
}
else{
collection[id][prop]=[value];
}
} else if (value !== ""){
collection[id][prop] = value;
} else {
delete collection[id][prop];
}
return collection;
}
if (collection[id][prop] !== "tracks") {
should be if (prop !== "tracks") {
function isLess(a, b) {
// Fix this code
return a===b;
}
// Change these values to test
isLess(10, 15);
hitmikey sends brownie points to @chrono79 and @magnesium-mike :sparkles: :thumbsup: :sparkles:
:star2: 1200 | @chrono79 |http://www.freecodecamp.com/chrono79
:cookie: 351 | @magnesium-mike |http://www.freecodecamp.com/magnesium-mike
@Chrono79 I guess I should read all of the requirements in the challenge so that i can logically assemble the code better right? for example, i had nested if's when i could've had it simplified as in the solution i posted.
i.e. i could've done a joint if statement like if XXX && XXX
var count = 0;
function cc(card) {
// Only change code below this line
switch (card) {
case 2,3,4,5,6:
return "5 Bet" ;
break ;
case 7,8,9 :
return "0 Hold";
break;
case 10,"J","Q","K","A" :
return "-5 Hold" ;
break;
case 3,7,"Q",8,"A" :
return "-1 Hold" ;
break ;
case 2,2,10 :
return "1 Bet" ;
break ;
case 2,"J",9,2,7:
return "1 Bet" ;
break ;
case 3,2,"A", 10,"K":
return "-1 Hold" ;
break ;
if (card==3){
return "-1 Hold";
} else if (card==7){
return"-1 Hold";
} else if (card=="Q") {
return "-1 Hold";
}else if (card==8) {
return "-1 Hold";
} else if (card=="A"){
return "-1 Hold";
}
}
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(3); cc(7); cc("Q"); cc(8); cc("A");
farenheit = (9/5)*celsius+32;
<
@Chipsta you can't use switch like that either
switch(card) {
case 2:
case 3:
...
}
and so on
:star2: 1201 | @chrono79 |http://www.freecodecamp.com/chrono79
endlessetudes sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
arguments[1]
@hrokr in this challenge, it didn't really talk about using multi dimension arrays in a for loop, it just gives the example. some feedback i'd give is that i'd prefer to have a little more explanation so that i can retain the concept and apply it to a future challenge:
:triangular_flag_on_post: Remember to use Read-Search-Ask
if you get stuck. Try to pair program :busts_in_silhouette: and write your own code :pencil:
This problem is a bit tricky because you have to familiarize yourself with Arguments, as you will have to work with two or more but on the script you only see two. Many people hardcode this program for three arguments. You will remove any number from the first argument that is the same as any other other arguments.
:pencil: read more about algorithm seek and destroy on the FCC Wiki
arguments[3]
jkilk sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1202 | @chrono79 |http://www.freecodecamp.com/chrono79
// Example
var ourStr = "I come first. ";
ourStr += "I come second.";
// Only change code below this line
var myStr = "This is the first sentence. " + "This is the second sentence.";
// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
// Only change code below this line;
var playerNumber = testObj[playerNumber]; // Change this Line
var player = testObj[16]; // Change this Line
function titleCase(str) {
var result;
var arr = str.toLowerCase().split(' ');
arr.map(function(val){
console.log(val.replace(val[0],val[0].toUpperCase()));
result = val.replace(val[0],val[0].toUpperCase());
}
);
return result;
}
titleCase("I'm a little tea pot”);
why does it return only the last element of the array?
nede36 sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1203 | @chrono79 |http://www.freecodecamp.com/chrono79
function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (answer) {
case 1:
console.log("alpha");
break;
case 2:
console.log("beta");
break;
case 3:
console.log("gamma");
break;
case 4:
console.log("delta");
break;
}
// Only change code above this line
return answer;
}
// Change this value to test
caseInSwitch(1);
answer
, but you are not setting anything in it. And you are doing switch(answer)
instead of using the val
...
caep2015 sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 1337 | @khaduch |http://www.freecodecamp.com/khaduch
khaduch sends brownie points to @caep2015 :sparkles: :thumbsup: :sparkles:
:cookie: 228 | @caep2015 |http://www.freecodecamp.com/caep2015
:warning: caep2015 already gave khaduch points
function checkCashRegister(price, cash, cid) {
var cost=arguments[0];
var money=arguments[1];
var till= arguments[2];
var count=0;
var change= money-cost;
for(var i in till){
count+= till[i].hasOwnProperty(val);
if(change>count){
return "Insufficient Funds";
}
}
return count;
}
caep2015 sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
@Chrono79 function caseInSwitch(val) {
var answer = "";
// Only change code below this line
switch (val) {
case 1:
console.log("alpha");
break;
case 2:
console.log("beta");
break;
case 3:
console.log("gamma");
break;
case 4:
console.log("delta");
break;
}
// Only change code above this line
return answer;
}
console.log
ing the answers. Instead, try to set answer =
to each case so that when you return answer
at the bottom it’s not empty.
case 1:
answer = "alpha";
and so on
jaywikid sends brownie points to @chrono79 and @bsandusky :sparkles: :thumbsup: :sparkles:
:cookie: 301 | @bsandusky |http://www.freecodecamp.com/bsandusky
:star2: 1204 | @chrono79 |http://www.freecodecamp.com/chrono79
// Example
var ourStr = "I come first. ";
ourStr += "I come second.";
// Only change code below this line
var myStr = "This is the first sentence. ";
ourStr += "This is the second sentence.";
var change= money-cost;
for(i=1; i<till.length;i+2){
count+= till[i];
if(change>count){
return "Insufficient Funds";
}
}
return count;
}
cid=[["PENNY", 1.01], ["NICKEL", 2.05] etc
for(i=0; i<till.length;i++){
for(j=1;j<till[i].length;j+2){
count+= till[j];
if(change>count){
return "Insufficient Funds";
}}
}
return count;
cid[i][1]
?
@micahbales - hello Micah - what is "strict" mode supposed to do? It doesn't seem to be any different from the normal mode?
It looks pretty good - sometimes the sounds don't play on repeated occurrences of the same color? And when I messed up on my round, I was expecting some kind of explosion or something? :)
function destroyer(arr) {
var destroyers = [];
for(var i = 1; i < arguments.length; i++){
destroyers.push(arguments[i]);
}
var destroyedArr = arr.filter(function(arrayValue){
for(var i = 0; i < destroyers.length; i++)
return arrayValue != destroyers[i];
});
return destroyedArr;
}
i'm trying this for the seek and destroy but i don't think the loop works, what should i look into replacing it with?
ie:
for (...
if (some condition )
return true
// after loop
return false
@JKilk
function testGreaterThan(val) {
if (val) { // Change this line
return "Over 100";
}
if (val) { // Change this line
return "Over 10";
}
return "10 or Under";
}
// Change this value to test
testGreaterThan(10);
findElement([ some array ], function( arg ) { code });
- it is the callback function for the filter method.
gkcodeman sends brownie points to @curlyws and @chrono79 :sparkles: :thumbsup: :sparkles:
:cookie: 201 | @curlyws |http://www.freecodecamp.com/curlyws
:star2: 1205 | @chrono79 |http://www.freecodecamp.com/chrono79
setInterrupt
and having some type of "event queue" would be a more consistent way of controlling the behavior? That's just another gut feeling - I'll see what happens when I get around to coding on this one! :)
function findElement(arr, func) {
, so func
will be the value of the function that you pass in, and you just use that as the callback, instead of writing Array.filter( function( value ) { whatever you are doing here; });
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
.red-text {
color: red;
}
h2 {
font-family: Lobster, Monospace;
}
p {
font-size: 16px;
font-family: Monospace;
}
.thick-green-border {
border-color: green;
border-width: 10px;
border-style: solid;
border-radius: 50%;
}
.smaller-image {
width: 100px;
}
</style>
<h2 class="red-text">CatPhotoApp</h2>
<img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat">
<p class="red-text">Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p>
<p class="red-text">Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.
</p>
<script>
$(document).ready(function() {
$("button").addClass("animated shake btn-primary")
$(".btn").addClass("animated shake btn-primary")
$("#target1").addClass("animated shake btn-primary")
});
</script>
<!-- Only change code above this line. -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
@khaduch ok I almost understand I think
but with this code,
function findElement(arr, func) {
console.log(num);
}
findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });
can you explain at what point the function takes 'num'. Do you have to declare num from outside the function? what if you never declare it?
<script>
in there? I forget - I'll have to go and look at that challenge...
setInterrupt
. Thanks, @khaduch
micahbales sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 1338 | @khaduch |http://www.freecodecamp.com/khaduch
.addClass()
method, as per the instructions. Not all three in each one.
.btn
(second way)function reverseString(str) {
return str;
}
var arr=[];
var str="";
str=reverseString("hello");
arr=str.split().reverse();
str=arr.join();
@PeRoXiiDe - no, the challenge is to use all three, but with a different class in each one.
Add the animated class to all elements with type
button
.Add the shake class to all the buttons with class
.btn
.Add the btn-primary class to the button with id
#target1
.
You have the selectors, you just have to remove the extraneous classes from each one.
checkCashRegister(20.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
Im trying to make a count only add the number vals of this arrayfunction reverseString
body.
gkcodeman sends brownie points to @name :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for name
function destroyer(arr) {
// Remove all the values
var args = Array.from(arguments);
args.splice(0,1);
return arr.filter(function(e){
return args.indexOf(e) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
peroxiide sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 1339 | @khaduch |http://www.freecodecamp.com/khaduch
jkilk sends brownie points to @byzgig :sparkles: :thumbsup: :sparkles:
:cookie: 326 | @byzgig |http://www.freecodecamp.com/byzgig
@gkcodeman @khaduch ok I almost understand I think
but with this code,
function findElement(arr, func) {
console.log(num);
}
findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });
can you explain at what point the function takes 'num'. Do you have to declare num from outside the function? what if you never declare it?
// 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);
curlyws sends brownie points to @mauriciocoder and @chrono79 :sparkles: :thumbsup: :sparkles:
:cookie: 296 | @mauriciocoder |http://www.freecodecamp.com/mauriciocoder
:star2: 1206 | @chrono79 |http://www.freecodecamp.com/chrono79
function whereAreYou(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
//console.log(Object.keys(collection).length);
for (var i = 0; i < Object.keys(collection).length; i++) {
for (var j = 0; j < Object.keys(source).length; j++) {
console.log(collection[i], source[j]);
}
}
// Only change code above this line
return arr;
}
whereAreYou([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
filter
method, you'll see that it always passes some parameters when it calls the callback. The first one (if I remember correctly) is the number or the array element that you are work on - the value of that array element.
:bulb: to format code use backticks! ``` more info
for (key in object)
you have the key of the object as a variable, so you just need to do object[key]
function findElement(arr, func) {
for(var i in arr){
if (func(arr[i])){
return arr[i];
}
}
}
findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });
for (var i = 0; i < Object.keys(collection).length; i++) {
for (var j = 0; j < Object.keys(source).length; j++) {
console.log(collection[i], Object.keys(source)[j]);
var test = Object.keys(source)[j];
console.log(test, collection[test]);
}
}
.filter
I guess. Like what you did, if it passes, it's good!
@CurlyWS - these are the key lines from my solution:
num = arr.filter(func);
return num.shift();
since filter returns an array, and we want to return the first element, I shift it off. I could probably simplify that to one line?
curlyws sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 1340 | @khaduch |http://www.freecodecamp.com/khaduch
return arr.filter(func).shift();
@khaduch maybe write
return arr.filter(func).shift();
?
return arr.filter(func)[0];
it's another way of doing the same
[0]
as Diego shows. Is that better, @Chrono79 ?
dagman sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1207 | @chrono79 |http://www.freecodecamp.com/chrono79
for
loop solutions - at least I saw someone posting something about that in some forum or text book. But I think that the statement was made that you shouldn't worry about speed unless you need to - I'm sure that if you're processing a million records or something, it's significant.
.shift()
while
loop
var decoded = "";
decoded += String.fromCharCode(str.charCodeAt(i+13));"
function findElement(arr, func) {
for(var i = 0, len = arr.length; i < len; i++) {
if(func(arr[i])) return arr[i];
}
return;
}
@dagman yeah very similar to my original solution
for(var i in arr){
if (func(arr[i])){
return arr[i];
}
}
but less elegant than using filer
function rot13(str) { // LBH QVQ VG!
var decoded = "";
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 77) {
decoded += String.fromCharCode(str.charCodeAt(i)+13);
}
else if (str.charCodeAt(i) >= 78 && str.charCodeAt(i) <= 90) {
decoded += String.fromCharCode(str.charCodeAt(i)-13);
}
else {decoded += String.fromCharCode(str.charCodeAt(i));
}
}
return decoded;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
65+(str.charCodeAt(0)+13)%65%13
function rot13(str) {
return str.split('').map(function(el) {
var code = el.charCodeAt(0);
if(code >= 65 && code <= 90 || code >= 97 && code <= 122){
return String.fromCharCode(getCorrectCode(el.charCodeAt(0) + 13));
}
return el;
}).join('');
function getCorrectCode(n) {
return n > 90 ? n = n - 26 : n;
}
}
def rot13(value)
return value.tr("a-z", "n-za-m")
end
myNoun + "abou
after the " for instanceWe will now use our knowledge of strings to build a "Mad Libs" style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence.
:pencil: read more about challenge word blanks on the FCC Wiki
var result = "";
// Your code below this line
// Your code above this line
return result;
It should be result
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
var result = "This is a " + myNoun + "about the lorem and the ipsum. They were "+ myAdjective +" travelers of time and space. However the lorem " + myVerb +" too fast for the Ipsum and left the ipsum behind. So the ipsum had to catch up " + myAdverb +"in order to keep up with the Lorem.";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("cat", "little", "hit", "slowly");
function titleCase(str) {
str.toLowerCase();
return str;
}
titleCase("I'm a little tea pot");
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
// Your code below this line
var result = "This is a " + myNoun + "about the lorem and the ipsum. They were "+ myAdjective +" travelers of time and space. However the lorem " + myVerb +" too fast for the Ipsum and left the ipsum behind. So the ipsum had to catch up " + myAdverb +"in order to keep up with the Lorem.";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("cat", "little", "hit", "slowly");
function FirstReverse(str) {
var reverse;
for(i=0;i<str.length+1;i++){
reverse[i] = (str[str.length-i]);
}
return str;
}
FirstReverse('Hello world');
return str.split().reverse().join();
vamshikrishna144 sends brownie points to @nixonrichard :sparkles: :thumbsup: :sparkles:
:cookie: 12 | @nixonrichard |http://www.freecodecamp.com/nixonrichard
vamshikrishna144 sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1208 | @chrono79 |http://www.freecodecamp.com/chrono79
mrburks sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1209 | @chrono79 |http://www.freecodecamp.com/chrono79
The toLowerCase() method to return the calling string value converted to lowercase.
The replace() method to return a new string with some or all matches of a pattern replaced by a replacement. We will use one of the RegExp we just created earlier.
The split() method splits a String object into an array of strings by separating the string into sub strings.
The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
The join() method joins all elements of an array into a string.
function myReplace(str, before, after) {
var After=after.split("");
if(before.charCodeAt(0)>95 && before.charCodeAt(0)<123 )
str=str.replace(before, after);
else if(before.charCodeAt(0)>64 && before.charCodeAt(0)<91){
if(after.charCodeAt(0)>64 && after.charCodeAt(0)<91){
str=str.replace(before, after);
}
else {
After=After.splice(0,1,String.fromCharCode(after.charCodeAt(0)-32));
After=After.join("");
str=str.replace(before,After);}
}
return str;
}
myReplace("A quick brown fox Jumped over the lazy dog", "Jumped", "leaped");
can someone explain to me this code for flattening an array,
var falttened = [].concat.apply([], arr);
what is the first parameter in apply doing (the [ ]) ? it doesn't seem to be doing anything?
javascript resources
You can add new properties to existing JavaScript objects the same way you would modify them. Here is how:
myDog.bark = "woof-woof";
:pencil: read more about challenge add new properties to a javascript object on the FCC Wiki
javascript resource
Chat Room Description | Chat Room |
---|---|
HTML/CSS/Bootstrap | FreeCodeCamp/Help |
JavaScript/Algorithms | FreeCodeCamp/HelpJavaScript |
Front End | FreeCodeCamp/HelpFrontEnd |
Data Visualization | FreeCodeCamp/HelpDataViz |
Back End | FreeCodeCamp/HelpBackEnd |
Choose the right room for your questions!
See also: :earth_asia: Language Specific | :satellite: Technology | :crystal_ball: Miscellaneous
zamua sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:star2: 1104 | @bitgrower |http://www.freecodecamp.com/bitgrower
Sorry, can't find a bonfire called falsy bouncer remove all falsy values from an array could this lead 2 a solution why doesnt it work yet. [ Check the map? ]
Nesting For Loops
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(var i=0; i<arr.length;i++){
for(var j=0; j<arr[i].length;j++){
product=product*arr[i];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
Bonfire, Falsy Bouncer, "Remove all falsy values from an array." Could this lead 2 a solution? & why doesn't it work (yet?) function bouncer(arr) {
for(var i=0; i<arr.length;i++){
if (new Boolean(arr[i])=false)
arr[i]=false;
}
}
var arrFiltered = arr.filter(bouncer);
return arrFiltered;
bouncer([7, "ate", "", false, 9]);
Sorry, can't find a bonfire called falsy bouncer remove all falsy values from an array could this lead 2 a solution why doesnt it work yet function bouncerarr forvar i0 iarrlengthi if new booleanarrifalse arrifalse var arrfiltered arrfilterbouncer return arrfilteredbouncer7 ate false 9. [ Check the map? ]
krishnakumar360 sends brownie points to @himanshu081996 :sparkles: :thumbsup: :sparkles:
:cookie: 263 | @himanshu081996 |http://www.freecodecamp.com/himanshu081996
new
I think
=
vs ==
function updateRecords(id, prop, value) {
if (value !== "" && prop !== "tracks"){
collection[id][prop]=value;
} else if (prop === "tracks" && value !== ""){
if (collection[id].hasOwnProperty(prop)){
collection[id][prop].push(value);
} else {
collection[id][prop]=[value];
}
} else {
delete collection[id][prop];
}
return collection;
}
@ranranking if(prop==="tracks" && value!==""){
if(collection[id][prop]){
collection[id][prop].push(value);
}
else{
collection[id][prop]=[value];
}
}
else if(value!==""){
collection[id][prop]=[value];
}
else{
delete collection[id][prop];
}
return collection;
}
@ranranking sorry there is some error in above code correct one is this function updateRecords(id, prop, value) {
if(prop==="tracks" && value!==""){
if(collection[id][prop]){
collection[id][prop].push(value);
}
else{
collection[id][prop]=[value];
}
}
else if(value!==""){
collection[id][prop]=value;
}
else{
delete collection[id][prop];
}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
function titleCase(str) {
str=str.toLowerCase();
str.substring(0,1)=str.substring(0,1).toUpperCase();
return str;
}
titleCase("I'm a little tea pot");
ranranking sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 1889 | @masd925 |http://www.freecodecamp.com/masd925
ranranking sends brownie points to @krishnakumar360 :sparkles: :thumbsup: :sparkles:
:cookie: 215 | @krishnakumar360 |http://www.freecodecamp.com/krishnakumar360
if(obj[key])
has problems.
1koenvdp sends brownie points to @kutsuya1 and @masd925 :sparkles: :thumbsup: :sparkles:
:cookie: 395 | @kutsuya1 |http://www.freecodecamp.com/kutsuya1
:star2: 1890 | @masd925 |http://www.freecodecamp.com/masd925
HTML
<div ng-repeat="s in selectedBooks" >
<p class="col-md-6">{{s.author}}</p>
<button class="btn btn-success confirmbtn" ng-model="tagName" ng-click="checkout(s.id); addBookID(s.id); updateDataBookID();">
Confirm
</button>
</div>
JS
$scope.bookid= [];
$scope.addBookID = function(id){
$scope.bookid.push({
name: $scope.id
});
};
console.log($scope.bookid);
$scope.updateDataBookID = function(){
$localStorage.bookTaken = $scope.bookid;
};
$scope.updateDataBookID();
but when in my local storage the value is null? any idea why?
function titleCase(str) {
str=str.toLowerCase();
str.substring(0,1)=str.substring(0,1).toUpperCase();
for (var i=1;i<=str.length-2;i++){
if (str[i] == " "){
str[i+1]=str[i+1].toUpperCase();
}
}
return str;
}
titleCase("I'm a little tea pot");
@Leodhy `function capitalize(s)
{
return s[0].toUpperCase() + s.slice(1);
}
function titleCase(str) {
var str_arr = str.split(' ');
for(var ii = 0; ii< str_arr.length; ii++){
var str_lower = str_arr[ii].toLowerCase();
str_arr[ii] = capitalize(str_lower);
console.log(str_arr[ii]);
}
return str_arr.join(' ');
}
titleCase("I'm a little tea pot");`
@ranranking ------- try this again -----function updateRecords(id, prop, value) {
if(prop==="tracks" && value!==""){
if(collection[id][prop]){
collection[id][prop].push(value);
}
else{
collection[id][prop]=[value];
}
}
else if(value!==""){
collection[id][prop]=value;
}
else{
delete collection[id][prop];
}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
function palindrome(str) {
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re,''));
var reverseStr = lowRegStr.split('').reverse('').join('');
return reverseStr === lowRegStr;
}
palindrome("eye");
@NixonRichard :smile:
lowRegStr.split('').reverse('').join('');
Should be
lowRegStr.split('').reverse().join('');
)
at the end of that line.
jamesmd sends brownie points to @arunkumrv and @masd925 :sparkles: :thumbsup: :sparkles:
:cookie: 553 | @arunkumrv |http://www.freecodecamp.com/arunkumrv
:star2: 1891 | @masd925 |http://www.freecodecamp.com/masd925
Just prey that Donald Trump
what ;)
cross domain
) we use a construct called padded JSON
(JSONP).
Objects have their own attributes, called properties_, and their own functions, called _methods.
You can use the this
keyword to reference public properties and methods of the current objects. However, when You need to create private ones so they are not accessible from the outside of the object you just remove the keyword this
from the object property or method declaration and declare it with var
so that it is private outside its scope.
var Bike = function() {
var speed = 100; // private
function addUnit(value) { // private
return value + "KM/H";
}
this.getSpeed = function () { // public
return addUnit(speed);
};
};
:pencil: read more about challenge make object properties private on the FCC Wiki
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 = 3;
this.getGear = function() {
return gear;
};
this.setGear = function(num) {
num = gear;
};
};
var myCar = new Car();
var myBike = new Bike();
shaunleow sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 1892 | @masd925 |http://www.freecodecamp.com/masd925
i want to generate an array of objects like this so how do i insert values dynamically
var array = [{
user-id : 5;
cars-id : ["2", "4","6"];
},{
user-id : 6;
cars-id : ["2", "4","6"];
}
];
user-id
in quotes. because if you don't put user-id
quotes, the JS interpreter will consider it as a subtraction.
var array = [{
'user-id': 5,
'cars-id' : ["2", "4","6"]
}];
var newObj = {
'user-id': 6,
'cars-id' : ["2", "4","6"]
}
array.push(newObj);
case-id
camelCase
convention instead of hyphen separated
convention.
userId
and caseId
,
not ;
.
,
and not ;
deepakpatil007 sends brownie points to @adityaparab and @arunkumrv :sparkles: :thumbsup: :sparkles:
:cookie: 284 | @adityaparab |http://www.freecodecamp.com/adityaparab
:cookie: 555 | @arunkumrv |http://www.freecodecamp.com/arunkumrv
can someone explain to me why this
console.log([1, [], [3, [[4]]]]);
is returning the 4 as an object?
Hi guys need help, I have this for loop,
for(var i = 0; i < balance.length;i++){
if(change > balance[i]){
coins.push(balance[i]);
change = change - balance[i];
}
}
what I want is to reset the loop when the conditions are met
change = change - balance[i]
i = 0;
[value]
. Putting that as an element to another array makes an array with an array as an element var arr=[[value]]
. You could get that value by arr[0][0]
.
var arr=[["catpants"]];
creates an array and assigns it to variable arr. It is an object. You can get the primitive value (string) out by accessing the array var str = arr[0][0];
. Variable str then has value "catpants"
.
"\t"
. Do that for each part of the sequence, and separate them by spaces (within one string)
@rudolfpablico I have done something a bit different here see if you can understand it
//if you use recursion you can create another loop
var balance = [2,3,4,5];
var change = 3;
coins = [];
cycle(0,10);
function cycle(i, limit){
if(limit===0){return "finished";}
for(i; i < balance.length;i++){
console.log(i);
if(change > balance[i]){
console.log("condition met");
coins.push(balance[i]);
change = change - balance[i];
limit--;
return cycle(0,limit);
}
}
}
I don't know if this solution is the best workaround though
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
case 'a';
return 'apple';
break;
case 'b':
return 'bird';
break;
case 'c':
return 'cat';
break;
default:'stuff';
// Only change code above this line
return answer;
}
// Change this value to test
switchOfStuff(2);
jprocks sends brownie points to @bkinahan :sparkles: :thumbsup: :sparkles:
:star2: 1675 | @bkinahan |http://www.freecodecamp.com/bkinahan
switch(...)
clause?
switch()
?
@BKinahan sorry but I am beginner
this is my string
var myStr = "\this \tis \tJavaScript \rtest \nstring for this challange!"
i didnt work
:(
monala sends brownie points to @bkinahan :sparkles: :thumbsup: :sparkles:
:star2: 1676 | @bkinahan |http://www.freecodecamp.com/bkinahan
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
if (value ===""){
delete collection[id][prop];
}
else if(prop !=="tracks"){
collection[id][prop]=value;
}
else if(prop ==="tracks") {
collection[id][prop].push(value);
}
return collection;
}
// Alter values below to test your code
updateRecords(1245, "album", "Robert Palmer");
collection[id][prop].push(value);
, it won't work, because it has no "tracks"
property defined. So you need to create it. read about .hasOwnProperty()
if you are not familiar with that :)
function largestOfFour(arr) {
// You can do this!
var x = 0;
var tmp = [];
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++){
if (arr[i][j] > arr[i][j+1]) {
tmp[x] = arr[i][j];
x++;
}
}
console.log(arr[i]);
}
return tmp;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
[value]
to tracks property. If true, just push the value to tracks array.
x
is not needed. Only obscures the logic. Something like this would work:
function largestOfFour(arr) {
// You can do this!
var tmp = [];
for (var i = 0; i < arr.length; i++){
tmp[i]=-Infinity;
for (var j = 0; j < arr[i].length; j++){
if (arr[i][j] > tmp[i]) {
tmp[i] = arr[i][j];
}
}
}
return tmp;
}
function convertToF(celsius) {
var fahrenheit;
// Only change code below this line
fahrenhett="celsius"*9/5+32;
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
celsius
in the equation without quotes. It is a parameter that holds the passed number (30 in the test case below the code).
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i = 0; i < multiplyAll.length; i++){
for(var j = 0; j < multiplyAll[i].length; j++){
console.log(multiplyAll[i]);
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);