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.
wjhurley sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 2024 | @moigithub |http://www.freecodecamp.com/moigithub
function convertToRoman(num) {
if (num.indexOf(num) === 1) {
num.push(num);
console.log('The numbers are : ' + num);
} else if (num.indexOf(num) > 1) {
console.log(num + ' is already included with the rest of the numbers.');
}
return num;
}
convertToRoman(36);
[i]
word length vs longest variable...
wheather[0]
then u can access description
weather.weather[0]
<-- return an object... and this object have a description propertyweather.weather[0].description
erayozer17 sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 2025 | @moigithub |http://www.freecodecamp.com/moigithub
function titleCase(str) {
var lol;
var arr = str.split(" "); // giving us ["hElLo","wOrld"];
for(i=0;i<arr.length;i++){
lol+=" "+arr[i].charAt(0).toUpperCase() + arr[i].slice(1).toLowerCase();
}
return lol;
}
titleCase("I'm a little tea pot");
function titleCase(str) {
var lol;
var arr = str.split(" "); // giving us ["hElLo","wOrld"];
for(i=0;i<arr.length;i++){
lol+=" "+arr[i].charAt(0).toUpperCase() + arr[i].slice(1).toLowerCase();
}
return lol;
}
titleCase("I'm a little tea pot");
kelifine sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 2026 | @moigithub |http://www.freecodecamp.com/moigithub
function titleCase(str) {
var lol;
var arr = str.split(" "); // giving us ["hElLo","wOrld"];
for(i=0;i<arr.length;i++){
lol+=" "+arr[i].charAt(0).toUpperCase() + arr[i].slice(1).toLowerCase();
}
return lol;
}
titleCase("I'm a little tea pot");
var lol = "";
beginnerdidi sends brownie points to @wjhurley :sparkles: :thumbsup: :sparkles:
:cookie: 284 | @wjhurley |http://www.freecodecamp.com/wjhurley
so this is what I noticed
whenever i'm face to face with a problem, i can't seem to solve it no matter how hard i try without someone's help. even then i struggle.
what do i do?
beginnerdidi sends brownie points to @errosc :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for errosc
function convertToRoman(num) {
var decimalValues = [1000, 900, 500];
var romanNumerals = ['M', 'CM', 'D'];
var romanized = '';
for (i = 0; i < values.length; i++) {
while (values[i] <= num) {
romanized + romanNumerals[i];
num -= value[i];
}
return num;
}
convertToRoman(36);
romanized + romanNumerals[i];
should be romanized += romanNumerals[i]
i < values.length;
whats values ?? i dont see u have that declared
function convertToRoman(num) {
var decimalValues = [1000, 900, 500];
var romanNumerals = ['M', 'CM', 'D'];
var romanized = '';
for (i = 0; i < decimalValues.length; i++) {
while (decimalValues[i] <= num) {
romanized + romanNumerals[i]
num -= decimalValues[i];
}
return num;
}
convertToRoman(36);
jonkiote sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 2028 | @moigithub |http://www.freecodecamp.com/moigithub
function convertToRoman(num) {
var decimalValues = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
var romanNumerals = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];
var romanized = '';
for (var i = 0; i < decimalValues.length; i++) {
while (decimalValues[i] <= num) {
romanized += romanNumerals[i]
num -= decimalValues[i];
}
return num;
}
convertToRoman(36);
return
statement?
num
.
function findLongestWord(str) {
var warr = str.split(' ');
var num = [];
for(var i = 0; i <= warr.length; i++)
{
num.push(warr[i].length);
}
return num;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
num
?
Hi again guys, I'm stuck at the quote machine challenge. I'm trying to get data from the API, but it's not working. This is a part of my code:
$http({
method: 'GET',
url: ' http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en'
}).then(function successCallback(response) {
alert("Test A!");
}, function errorCallback(response) {
alert("Test B!");
});
:star2: 2029 | @moigithub |http://www.freecodecamp.com/moigithub
ashrisoft sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
[]
. Now how can I make this thing run in the conslole, whatever it is?function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
for (var prop in arr) {
if (hasOwnProperty.call(arr, prop)) {
result.push(prop);
} else if (Object.prototype.hasOwnProperty.call(source, collection)) {
target[collection] = source[collection];
} else {
return target;
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
var arr = []; for (var prop in arr) { ... }
arr
is empty
for
loop?
arr
arr
is always empty
function whatIsInAName(collection, source) {
var arr = [];
return arr;
}
magikid sends brownie points to @daulis809 :sparkles: :thumbsup: :sparkles:
:cookie: 190 | @daulis809 |http://www.freecodecamp.com/daulis809
[]
in the console. How can I fix this code I have here so that way it can run?
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
for (var prop in arr) {
if (hasOwnProperty.call(arr, prop)) {
result.push(prop);
} else if (Object.prototype.hasOwnProperty.call(source, collection)) {
target[collection] = source[collection];
} else {
return target;
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
arr.length
?
arr
?
Hey all, I'm having a problem with the "Record Collection" task. For reference: https://www.freecodecamp.com/challenges/record-collection
Here's what I have so far. Would someone mind giving me a hint/pointing me in the right direction? http://codepen.io/anon/pen/qNZPmX
id
value, it should be indexing into the collection to access particular objects - collection[id]
- that would be a place to start. Look at how you are accessing collection
- the id
value alone really cannot be used on its own.
I'm still having a problem with Wherefore Art Thou. The code:
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
for (var prop in arr) {
if (hasOwnProperty.call(arr, prop)) {
result.push(prop);
} else if (Object.prototype.hasOwnProperty.call(source, collection)) {
target[collection] = source[collection];
} else {
return target;
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
It's not running. What can I do to fix it?
arr
- you are trying to iterate through it with that for
statement, but ...?
for
statement.
arr
contain? It looks like a variable that you should be using to accumulate results, because that is what you are supposed to return. It starts out as an empty array? Nothing to iterate through?
arr
?
adamjubert sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 1591 | @khaduch |http://www.freecodecamp.com/khaduch
arr
should eventually hold the objects that meet the test condition - for this example call, anything with { last: "Capulet" }
as part of an object should be copied to arr
during your code execution.
for
loop instead?
collection
argument, so I think that your for
loop should be used to iterate over collection
.
@khaduch I used the for
loop to iterate over collection
but I got a message saying that a target is not defined.
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
for (var prop in collection) {
if (hasOwnProperty.call(arr, prop)) {
result.push(prop);
} else if (Object.prototype.hasOwnProperty.call(source, collection)) {
target[collection] = source[collection];
} else {
return target;
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
How can I define a target?
@khaduch http://codepen.io/anon/pen/qNZPmX
It's something with line 34, but I can't figure out what.
hasOwnProperty.call(arr, prop)
... actually do?
arguments
(hasOwnProperty.call(arr, prop))
(Object.prototype.hasOwnProperty.call(source, collection))
(hasOwnProperty.call(arr, prop))
is actually doing anything.
result.push(prop);
... wouldn't do anything because there is no result
s variable.
hasOwnProperty
as a built in Object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
@adamjubert - you must review the lessons on accessing object properties with dot notation and bracket notation - particularly this one: "Accessing Objects Properties with Variables" - since that is what you need to be doing here, as the id
and prop
are passed in using the function arguments, which are variables that you use. (Hint: collection.id
is not correct, since there is no property in collection named id
.) Please review those lessons - it is an important concept!
UPDATE : I see that you realized that...
hasOwnProperty
?
Object.prototype.hasOwnProperty()
method.
result
variable. Also.. What is target
? I don't see that you've defined it anywhere. But, you're return
ing it.
adamjubert sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:warning: adamjubert already gave khaduch points
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
for (var result = 0; result < collection.length; result++) {
if (hasOwnProperty.call(arr)) {
result.push(arr);
} else if (Object.prototype.hasOwnProperty.call(source, collection)) {
target[collection] = source[collection];
} else {
return target;
}
}
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
collection.id
instead of collection[id]
???
tracks
on that particular collection[id]
in the situation where you do not have "tracks" there. So you can just to collection[id].tracks = [];
and then push to that. collection[id].tracks.push(value);
OR you can do it all in one move with collection[id].tracks = [value];
adamjubert sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:warning: adamjubert already gave khaduch points
@LisaRamos - I have to stop, it's late, but I'll just try to direct you in a better direction - instead of naming your for
loop variable result
, which is misleading, just name it i
- it is going to be an index through the collection array. Then something like this:
for ( var i = 0; i < collection.length; i++ ) {
// now you want to check the collection element that you are looking at for the existence and content of properties
if ( collection[i].hasOwnProperty( whatever_property_you_need_to_check ) && collection[i][whatever_property_you_need_to_check] === source[ whatever_property_you_need_to_check] ) {
// you have a matching property and value - this is what you need to be able to add the current object to the result `arr`.
arr.push(collection[i]);
}
}
That doesn't get you the entire solution, there is a little more complexity, and I'm sorry it if confuses you even more - but you need to do something like that in order to create the solution to this challenge.
Note that the "whatever_property_you_need_to_check" properties are those properties of the object in the source
function argument. You have to have each of the same property and same value that exist in the source
in each of the collection
objects in order to add it to the solution set, stored in arr
, which is what will eventually be returned to the caller of the function.
tonnamb sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 2030 | @moigithub |http://www.freecodecamp.com/moigithub
source
objects have multiple properties. So you have to set up a loop within the for loop that is iterating over the collection, and then keep track of whether or not all of the properties and values that they contain match. I think that is a bit of a leap in solving this challenge. IT is similar to the other collection challenge with the contacts and firstName
matching - you cannot just jump and do something (as in that challenge with return "no such contact";
) until you have ferreted out all of the possible matches and mismatches. In fact, in my solution, I kept two variables "matches" and "mismatches", and if there was a property match, I incremented "matches", and if there was a miss, I incremented "mismatches". Then at the end, something like if ( matches && !mismatches) { arr.push(collection[i]); }
Just a bit of bookkeeping to fully recognize that the object should be kept in the solution array...
adventurebear sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 1592 | @khaduch |http://www.freecodecamp.com/khaduch
for(var i = 0; i < arr.length; i++){
for(var a = 0; a < arr.length; a++){
/* Do something here */
}
}
}
in the wrong place.
nevaisdreaming sends brownie points to @alexanderkopke :sparkles: :thumbsup: :sparkles:
:cookie: 727 | @alexanderkopke |http://www.freecodecamp.com/alexanderkopke
@purelight4ever for certain records the property tracks could not exist, so you have to create it first
If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the album's corresponding property.
https://www.freecodecamp.com/challenges/testing-objects-for-properties
https://www.freecodecamp.com/challenges/add-new-properties-to-a-javascript-object
beginnerdidi sends brownie points to @alexanderkopke :sparkles: :thumbsup: :sparkles:
:cookie: 728 | @alexanderkopke |http://www.freecodecamp.com/alexanderkopke
purelight4ever sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1927 | @chrono79 |http://www.freecodecamp.com/chrono79
purelight4ever sends brownie points to @alexanderkopke :sparkles: :thumbsup: :sparkles:
:cookie: 729 | @alexanderkopke |http://www.freecodecamp.com/alexanderkopke
purelight4ever sends brownie points to @alexanderkopke :sparkles: :thumbsup: :sparkles:
:warning: purelight4ever already gave alexanderkopke points
```var lowCase = arr.toString().toLowerCase();
var split = lowCase.split(",");
if(lowCase.indexOf(split[1]) === 0){
console.log(lowCase,split[1]);
return true;
}else if(lowCase.indexOf(split[1]) === -1) return false;```
telephoneCheck("1 555-555-5555");
function telephoneCheck(str) {
str = str.replace("/\s/g","");
//(555)555-5555
if (/^1?[(][0-9][0-9][0-9][)][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9]/m.test(str)) return true;
//55555555555
if (/^1?[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$/m.test(str)) return true;
//555-555-5555
if (/^1?[0-9][0-9][0-9][-][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9]$/m.test(str)) return true;
return false;
}
"/\s/g"
that should not be in quotation marks
@acloud12345678 surround ur code with this (minus the exclamation marks)
`!```javascript
`!```code here
erickzhao sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star2: 1381 | @qualitymanifest |http://www.freecodecamp.com/qualitymanifest
acloud12345678 sends brownie points to @erickzhao :sparkles: :thumbsup: :sparkles:
:cookie: 300 | @erickzhao |http://www.freecodecamp.com/erickzhao
`
// Example
var ourArray = [1,2,3];
var removedFromOurArray = ourArray.pop();
// removedFromOurArray now equals 3, and ourArray now equals [1,2]
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line.
var removedFromMyArray;
var removedFromMyArray = myArray.pop();
```
How to do code block format:
```js [SHIFT+ENTER]
// your code here
```[CTRL+ENTER or CMD+ENTER to send]
Please do not confuse `s with 's.
Also note that the ```s need to each be on their own lines
The ` key can usually be found on most keyboards up next to the 1 key.
If you hit SHIFT+` it will give you the ~.
Example:
```
code
```
...
Output:
var code = undefined;
...
You can also do inline code
formatting:
A string of text with a `variable` or `other bit of code`.
Output:
A string of text with a variable
or other bit of code
.
// Example
var ourArray = [1,2,3];
var removedFromOurArray = ourArray.pop();
// removedFromOurArray now equals 3, and ourArray now equals [1,2]
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line.
var removedFromMyArray;
var removedFromMyArray = myArray.pop();
acloud12345678 sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 1760 | @revisualize |http://www.freecodecamp.com/revisualize
var removedFromMyArray;
Remove this one line and it should work.
acloud12345678 sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:warning: acloud12345678 already gave revisualize points
indexOf
call is just comparing arr.toString().toLowerCase()
to the 2nd index of arr
, put to all lowercase letters. You also don't have a return value for your function if your two if
conditions aren't met. From what I recall, you should be looping through each individual letter to see if it's present in the other string, since you're comparing all characters within the two parameters.
i need help with Write Reusable JavaScript with Functions
```js
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
var reusableFunction("Hi Wolrd");
function myFunction(parameters){
//function body
}
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
function myFunction(){
myFunction("Hi World");
}
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
function myFunction(){
reusableFunction(){
console.log("Hi World");
}
}
function cpu() { //CPU move chosen from random choice var
if (userX) {
if (answer.indexOf("A") >= 0 && answer.indexOf("C") >= 0) {
$("#B").text("O").css("color", "blue");
} else if (answer.indexOf("A") >= 0 && answer.indexOf("I") >= 0) {
$("#E").text("O").css("color", "blue");
} else if (answer.indexOf("A") >= 0 && answer.indexOf("G") >= 0) {
$("#D").text("O").css("color", "blue");
} else if (answer.indexOf("B") >= 0 && answer.indexOf("H") >= 0) {
$("#E").text("O").css("color", "blue");
} else if (answer.indexOf("C") >= 0 && answer.indexOf("I") >= 0) {
$("#F").text("O").css("color", "blue");
} else if (answer.indexOf("C") >= 0 && answer.indexOf("G") >= 0) {
$("#E").text("O").css("color", "blue");
} else if (answer.indexOf("D") >= 0 && answer.indexOf("F") >= 0) {
$("#E").text("O").css("color", "blue");
} else {
$("#" + choice + "").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase()); console.log(cpuAnswer);
}
QUESTION:
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
function reusableFunction() {
reusableFunction(); {
console.log("Hi World");
}
}
myFunction()
should look exactly like ourReusableFunction()
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
//this line below is where you named the function. Good!
function reusableFunction() {
//this line below is not needed
reusableFunction(); {
console.log("Hi World");
}//this bracket isnt needed either
}
reusableFunction();
on a line will execute all the code within the reusableFunction
function declaration
// Example
function ourReusableFunction() {
console.log("Heyya, World");
}
ourReusableFunction();
// Only change code below this line
function reusableFunction() {
//this line below is not needed
console.log("Hi World");
}
acloud12345678 sends brownie points to @thalletprotech :sparkles: :thumbsup: :sparkles:
:cookie: 243 | @thalletprotech |http://www.freecodecamp.com/thalletprotech
acloud12345678 sends brownie points to @erickzhao :sparkles: :thumbsup: :sparkles:
:warning: acloud12345678 already gave erickzhao points
function cpu() { //CPU move chosen from random choice var
if (userX) {
if (answer.indexOf("A") >= 0 && answer.indexOf("C") >= 0) {
$("#B").text("O").css("color", "blue");
} else if (answer.indexOf("A") >= 0 && answer.indexOf("I") >= 0) {
$("#E").text("O").css("color", "blue");
}
} else { //if human not 1 move from winning pick randomly
$("#" + choice + "").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase()); console.log(cpuAnswer);
}
QUESTION:Ok because I complete the challenge, to add all elements together, and I didn't add any number at the end, and it works perfectly fine. But thanks guys. var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
singleVal = array.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
});
//variables section
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 4;
var paddle1Y = 250;
const PADDLE_HEIGHT = 100;
// C Programming #define (ALWAYS CONSTANT)
/*
Observing returning event (evt) of mouse positioning coordinates in relation to where the mouse is on the "gameCanvas"
For example starting point on the "gameCanvas" is on (0,0) on the (y,x) axis
EventListener wouldn't care about mouse position or "mousePos" if this code wasn't here
Two piece of data are being returned here... mouseX and mouseY
*/
function calculateMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return {
x:mouseX,
y:mouseY
};
}
//variables section
//Speed of objects & EventListener & Resetting the Ball section
window.onload = function () {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
var framesPerSecond = 30;
setInterval(function() {
moveEverything();
drawEverything();
}, 1000/framesPerSecond );
canvas.addEventListener('mousemove',
function(evt) {
var mousePos = calculateMousePos(evt);
paddle1Y = mousePos.y-(PADDLE_HEIGHT/2); //So players mouse and paddle relationship position is center
});
}
function moveEverything() {
ballX = ballX + ballSpeedX;
ballY = ballY + ballSpeedY
if(ballX < 0) {
if(ballY > paddle1Y &&
ballY < paddle1Y+PADDLE_HEIGHT) {
ballSpeedX = -ballSpeedX;
} else {
ballReset(); }
if(ballX > canvas.width) {
ballSpeedX = -ballSpeedX;
}
if(ballY < 0) {
ballSpeedY = -ballSpeedY;
}
if(ballY > canvas.height) {
ballSpeedY = -ballSpeedY;
}
//Speed of objects & EventListener & Resetting the Ball section
//Ball Reset f(x) section
function ballReset() {
ballSpeedX = -ballSpeedX;
ballX = canvas.width/2;
ballY = canvas.height/2;
}
//Ball Reset f(x) section
//canvas arguments/parameters
function drawEverything () {
// next line blanks out the screen with black
colorRect(0,0,canvas.width,canvas.height,'black');
// this left player paddle
colorRect(0,paddle1Y,10,100,'white');
// next line draws the ball
colorCircle(ballX,ballY,10,'white');
}
function colorCircle(centerX, centerY, radius, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.beginPath();
canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
canvasContext.fill();
}
function colorRect(leftX,topY, width,height, drawColor) {
canvasContext.fillStyle = drawColor;
canvasContext.fillRect(leftX,topY, width,height);
}
//canvas arguments/parameters
I'm having trouble in understanding string immutability and I'm not sure what needs to be fixed in this code // Setup
var myStr = "Jello World";
// Only change code below this line
myStr[0] = "H"; // Fix Me
function destroyer(arr) {
// Remove all the values
var firstArray = arguments;
for (var i = 0; i < arguments.length; i++) {
firstArray.push(arguments[i]);
}
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
var firstArray = Array.from(arguments)
[1, 2, 3, 1, 2, 3]
- the 1st arguments - just say arr(the parameter of the function)
is this correct
// Setup
var myStr = "Jello World";
// Only change code below this line
myStr = "Hello";
myStr[0] = "H"; // Fix Me
// You need to totally rewrite the string - since it is immutable
my Str = "Hello World";
// or
myStr = myStr.replace("J","H");
@billpzt if you want[1, 2, 3, 1, 2, 3]
- the 1st arguments - just sayarr(the parameter of the function)
@jamesmillerho but the problem is I don't know in advance how many arguments they're going to give me. I know the first is supposed to be an array, but then how do I handle the others if I don't know how many of them there'll be? THat's why I thought of making a loop and pushing each thing into a new array, which didn't work as expected...
arguments
to an array in that exercise, the first element is an array, and the remaining elements are the elements to be added to it
arr
- just use the common slice funcitonArray.from(arguments).slice(1);
surya96t sends brownie points to @jamesmillerho :sparkles: :thumbsup: :sparkles:
:cookie: 407 | @jamesmillerho |http://www.freecodecamp.com/jamesmillerho
@billpzt Array.from(arguments) will take all
@jamesmillerho cool, will try that
@patricktownley I know, that's a big part of what got me confused
billpzt sends brownie points to @jamesmillerho and @patricktownley :sparkles: :thumbsup: :sparkles:
:cookie: 408 | @jamesmillerho |http://www.freecodecamp.com/jamesmillerho
:cookie: 282 | @patricktownley |http://www.freecodecamp.com/patricktownley
function destroyer(arr){
var extra = Array.from(arguments).slice(1);
return arr.filter(function(a){return !extra.includes(a);});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
[1,2,3,1,2,3], 2, 3
. It isn't an array. You already have the initial array, it's named as arr
.
arr
is that array. Those numbers aren't named
else if (answer.indexOf("D") >= 0 && answer.indexOf("F") >= 0) {
$("#e").text("O").css("color", "blue");
if (answer.indexOf("E") >= 0 || cpuAnswer.indexOf("E") >= 0) {
$("#" + choice + "").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
}
else if (answer.indexOf("H") >= 0 && answer.indexOf("I") >= 0) {
$("#g").text("O").css("color", "blue");
if (answer.indexOf("G") >= 0 || cpuAnswer.indexOf("G") >= 0) {
$("#" + choice + "").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
}else {
$("#" + choice + "").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
console.log(cpuAnswer);
}
The computer will console.log the correct move in certain situations but wont place its O in the box. Can you help me debug this?arguments
object:var elementsToRemove = Array.from(arguments).slice(1);
arguments
is a collection of all the arguments. But you can't do much with it because it isn't an array, so you need to make it into an array.
:cookie: 291 | @ricardomga |http://www.freecodecamp.com/ricardomga
jeremyredkey sends brownie points to @ricardomga :sparkles: :thumbsup: :sparkles:
arr
function calculateMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return {
x:mouseX,
y:mouseY
};
}
billpzt sends brownie points to @dancouper and @patricktownley :sparkles: :thumbsup: :sparkles:
:cookie: 198 | @dancouper |http://www.freecodecamp.com/dancouper
:warning: billpzt already gave patricktownley points
p.globalCompositeOperation = "source-over";
p.fillStyle = "rgba(0, 0, 0, 0.5)";
p.fillRect(0,0,w,h);
p.globalCompositeOperation = "lighter";
how p.fillStyle = "rgba(0, 0, 0, 0.5)";
gives the effect?
function largestOfFour(arr) {
var results =[];
for (i = 0 ; i<arr.length; i++){
var largestNumber;
for(j = 0 ; j<arr[i].length; j++){
if(arr[i][j]>largestNumber){
largestNumber=arr[i][j];
results+=[largestNumber];
}
}
}
return results;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
your results
is an Array
. Not a string or number.
results+=[largestNumber];
is not how you add elements to the array
.push
function.
@adityaparab Thanks mate. Done!
function largestOfFour(arr) {
var results =[];
for (i = 0 ; i<arr.length; i++){
var largestNumber = 0;
for(j = 0 ; j<arr[i].length; j++){
if(arr[i][j]>largestNumber){
largestNumber=arr[i][j];
}
}
results.push(largestNumber);
}
return results;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
I know there is a Math.max() as well, although I find it rather problematic to put it to work with multi-dimensional arrays, any pointer as to how to?
jadczakd sends brownie points to @adityaparab :sparkles: :thumbsup: :sparkles:
:cookie: 635 | @adityaparab |http://www.freecodecamp.com/adityaparab
function titleCase(str) {
var arrStr= str.split(" ");
var titleStr=[];
for (var i=0;i<arrStr.length;i++){
titleStr += arrStr[i].charAt(0).toUpperCase() + arrStr[i].slice(1).toLowerCase();
titleStr+= " ";
}
titleStr.trim();
return titleStr;
}
titleCase("sHoRt AnD sToUt");
@jadczakd : Perfect mate!
Here is another way to do it. :D
function largestOfFour(arr) {
return arr.map(function(a){
return Math.max.apply(null, a);
});
}
Array
. titleStr +=
is not how you add elements to the array. You will need to use .push
instead.
val
(the key) and return value for that key.
function cpu() { //CPU move chosen from random choice var
if (userX) {
if (choices.length < 1) {
alert("DRAW GAME");
end();
}
if (answer.indexOf("A") >= 0 && answer.indexOf("C") >= 0&& answer.indexOf("B") <= 0 || cpuAnswer.indexOf("B") <= 0) {
$("#b").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
} else if (answer.indexOf("A") >= 0 && answer.indexOf("I") >= 0&& answer.indexOf("E") <= 0 || cpuAnswer.indexOf("E") <= 0) {
$("#e").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
} else if (answer.indexOf("A") >= 0 && answer.indexOf("G") >= 0&& answer.indexOf("D") <= 0 || cpuAnswer.indexOf("D") <= 0) {
$("#d").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
} else if (answer.indexOf("B") >= 0 && answer.indexOf("H") >= 0&&answer.indexOf("E") <= 0 || cpuAnswer.indexOf("E") <= 0) {
$("#e").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
else if (answer.indexOf("C") >= 0 && answer.indexOf("I") >= 0&&answer.indexOf("F") <= 0 || cpuAnswer.indexOf("F") <= 0) {
$("#f").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
} else if (answer.indexOf("C") >= 0 && answer.indexOf("G") >= 0&&answer.indexOf("E") <= 0 || cpuAnswer.indexOf("E") <= 0) {
$("#e").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
} else if (answer.indexOf("C") >= 0 && answer.indexOf("B") >= 0&& answer.indexOf("A") <= 0 || cpuAnswer.indexOf("A") <= 0) {
$("#a").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
else if (answer.indexOf("E") >= 0 && answer.indexOf("F") >= 0&&answer.indexOf("D") <= 0 || cpuAnswer.indexOf("D") <= 0) {
$("#d").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
else if (answer.indexOf("D") >= 0 && answer.indexOf("F") >= 0&&answer.indexOf("E") <= 0 || cpuAnswer.indexOf("E") <= 0) {
$("#e").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
else if (answer.indexOf("H") >= 0 && answer.indexOf("I") >= 0&&answer.indexOf("G") <= 0 || cpuAnswer.indexOf("G") <= 0) {
$("#g").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
}
else {
$("#" + choice + "").text("O").css("color", "blue");
cpuAnswer.push(choice.toUpperCase());
console.log(cpuAnswer);
}}
if (cpuAnswer.indexOf("A") >= 0 && cpuAnswer.indexOf("B") >= 0 && cpuAnswer.indexOf("C") >= 0) {
alert("you win!");
setTimeout(function() { end() }, 400);
} else if (cpuAnswer.indexOf("D") >= 0 && cpuAnswer.indexOf("E") >= 0 && cpuAnswer.indexOf("F") >= 0) {
alert("Cpu win!");
setTimeout(function() { end() }, 400);
} else if (cpuAnswer.indexOf("G") >= 0 && cpuAnswer.indexOf("H") >= 0 && cpuAnswer.indexOf("I") >= 0) {
alert("Cpu win!");
setTimeout(function() { end() }, 300);
} else if (cpuAnswer.indexOf("A") >= 0 && cpuAnswer.indexOf("D") >= 0 && cpuAnswer.indexOf("G") >= 0) {
alert("CPU win!");
setTimeout(function() { end() }, 300);
} else if (cpuAnswer.indexOf("B") >= 0 && cpuAnswer.indexOf("E") >= 0 && cpuAnswer.indexOf("H") >= 0) {
alert("CPU win!");
setTimeout(function() { end() }, 300);
} else if (cpuAnswer.indexOf("C") >= 0 && cpuAnswer.indexOf("F") >= 0 && cpuAnswer.indexOf("I") >= 0) {
alert("CPU win!");
setTimeout(function() { end() }, 400);
} else if (cpuAnswer.indexOf("A") >= 0 && cpuAnswer.indexOf("E") >= 0 && cpuAnswer.indexOf("I") >= 0) {
alert("CPU win!");
setTimeout(function() { end() }, 400);
} else if (cpuAnswer.indexOf("C") >= 0 && cpuAnswer.indexOf("E") >= 0 && cpuAnswer.indexOf("G
Can you helpwith this bracket problem? I just cant find the bug? It says unexpected else statement
Hi. I don't understand what I am supposed to do.... I'm on Chapter "Record Collection"..... And the task is quite vague.... If someone can explain is to me or can give me any kind of Hint...
Record Collection
You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique id number as its key. Not all albums have complete information.
Write a function which takes an album's id (like 2548), a property prop (like "artist" or "tracks"), and a value (like "Addicted to Love") to modify the data in this collection.
If prop isn't "tracks" and value isn't empty (""), update or set the value for that record album's property.
Your function must always return the entire collection object.
There are several rules for handling incomplete data:
If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the album's corresponding property.
If prop is "tracks" and value isn't empty (""), push the value onto the end of the album's existing tracks array.
If value is empty (""), delete the given prop property from the album.
name
is "Joseph" console.log "Joseph is awesome".if (name === "Joseph") {
console.log("Joseph is awesome");
}
// AddressBook is a class?
function AddressBook() {
this.contacts = [];
}
// is this creats a custom function under AddressBook construcotr?
AddressBook.prototype.addContact = function(contact) {
this.contacts.push(contact);
}
danydin sends brownie points to @polak90 :sparkles: :thumbsup: :sparkles:
:cookie: 140 | @polak90 |http://www.freecodecamp.com/polak90
unction Dog(name, type){
this.name = name;
this.type = type;
this.bark = function(){
alert(this.name + " barks");
};
this.growl = function(){
alert(this.name + " growls");
};
this.getBreed = function(){
return this.type;
};
}
var lassie = new Dog("Lassie", "Collie");
lassie.bark(); // Lassie bark
lassie.growl(); // Lassie growls
var breed = lassie.getBreed(); // Collie
var rintintin= new Dog("Rin Tin Tin", "German Shepard");
rintintin.bark(); // Rin Tin Tin barks
rintintin.growl(); // Rin Tin Tin growls
var breed = rintintin.getBreed(); // German Shepard
function Dog(name, type){
this.name = name;
this.type = type;
}
Dog.prototype.bark = function(){
alert(this.name + " barks");
}
Dog.prototype.growl= function(){
alert(this.name + " growls");
}
Dog.prototype.getBreed = function(){
return this.type;
}
var lassie = new Dog("Lassie", "Collie");
lassie.bark(); // Lassie barks
lassie.growl(); // Lassie growls
var breed = lassie.getBreed(); // Collie
var rintintin= new Dog("Rin Tin Tin", "German Shepard");
rintintin.bark(); // Rin Tin Tin bark
rintintin.growl(); // Rin Tin Tin growls
var breed = rintintin.getBreed(); // German Shepard
@revisualize
function updateRecords(id, prop, value) {
if (value === '') {
delete collection[id][prop];
} else if (prop !== 'tracks') {
collection[id][prop] = value;
} else {
collection[id][prop].push(value);
}
One task is still not being checked and I don't get it why...
@moyo92 : Yeah, checked your code, you'd need to do either
titleStr = titleStr.trim();
return titleStr;
or simply
return titleStr.trim();
engaged
(and never marry) you won't have to worry about it for the rest of your life
moyo92 sends brownie points to @adityaparab :sparkles: :thumbsup: :sparkles:
:cookie: 636 | @adityaparab |http://www.freecodecamp.com/adityaparab
.trim
returns new modified string and doesn't modify the actual string you called the function on.
canvas > svg
@ReadyDoMe
@adityaparab i asked and then they kept talking about painting their nails
Let me guess,, are you American?
@adityaparab // Only change code below this line
var processArg = 7;
var processed;
function processArg(num){
return (processed);
}
@adityaparab Assume we have pre-defined a function sum which adds two numbers together, then:
ourSum = sum(5, 12);
will call sum function, which returns a value of 17 and assigns it to ourSum variable.
Instructions
Call the processArg function with an argument of 7 and assign its return value to the variable processed.
:trollface: troll problems? notify admins here
@qmikew1
so, anyway... clearly you don't understand how this works. People help you because they are nice or volunteering to do so ... drop the entitlement and it works much better
That's exactly what makes me wonder if he's American :P
@ReadyDoMe :
All you need is this
function processArg(num){
return num;
}
processArg(...); //<----------
// Example
var changed = 0;
function change(num) {
return (num + 5) / 3;
}
changed = change(10);
// Setup
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
processed = processArg(7);
engaged
.
adityaparab sends brownie points to @polak90 :sparkles: :thumbsup: :sparkles:
:cookie: 141 | @polak90 |http://www.freecodecamp.com/polak90
@polak90
return by pointer
Nope! By reference
ya ok got ur point
or point(er) ;)
adamtakacs05 sends brownie points to @lunjwaba1 :sparkles: :thumbsup: :sparkles:
:cookie: 289 | @lunjwaba1 |http://www.freecodecamp.com/lunjwaba1
@hacu9 :
var allExceptFirst = Array.prototype.slice.call(arguments, 1);
will give you last elements.
readydome sends brownie points to @bkinahan :sparkles: :thumbsup: :sparkles:
:star2: 2317 | @bkinahan |http://www.freecodecamp.com/bkinahan
hacu9 sends brownie points to @adityaparab and @wearenotgroot :sparkles: :thumbsup: :sparkles:
:cookie: 637 | @adityaparab |http://www.freecodecamp.com/adityaparab
:star2: 1476 | @wearenotgroot |http://www.freecodecamp.com/wearenotgroot
>==
or <==
push
/ pop
, shift
/ unshift
?
How to do code block format:
```js [SHIFT+ENTER]
// your code here
```[CTRL+ENTER or CMD+ENTER to send]
Please do not confuse `s with 's.
Also note that the ```s need to each be on their own lines
The ` key can usually be found on most keyboards up next to the 1 key.
If you hit SHIFT+` it will give you the ~.
Example:
```
code
```
...
Output:
var code = undefined;
...
You can also do inline code
formatting:
A string of text with a `variable` or `other bit of code`.
Output:
A string of text with a variable
or other bit of code
.
adityaparab sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 1761 | @revisualize |http://www.freecodecamp.com/revisualize
"Open sesame"
ends with "same"
. See the last four letters? They're the same ;)
.substr
function and read about what positive and negative parameters mean.
"Never give up and good luck will find you."
moyo92 sends brownie points to @adityaparab :sparkles: :thumbsup: :sparkles:
:warning: moyo92 already gave adityaparab points
.push
function for
push
/ pop
, shift
/ unshift
Hi Guys,
I was doing ...
https://www.freecodecamp.com/challenges/build-a-random-quote-machine
This is my pen:
http://codepen.io/Ishma-Reyhool/pen/pyZJvx
Could someone tell me why my color change feature at the very bottom isn't working.
arr
) and a number (item
) as arguments.
backItter
to 1
every time the function runs.
// this is the class?
var Person = function () {
// and this is the Constructor?
console.log('instance created');
};
return this === that;
<=
gk0r sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 1762 | @revisualize |http://www.freecodecamp.com/revisualize
jamesmillerho sends brownie points to @zzpot :sparkles: :thumbsup: :sparkles:
:cookie: 318 | @zzpot |http://www.freecodecamp.com/zzpot
hi guys i need some help at repeat a string....
i mean : repeatStringNumTimes("", 3) should return "**".
and this is the code:
function repeatStringNumTimes(str, num) {
// repeat after me
return str;
}
repeatStringNumTimes("abc", 3);
i didnt understood very well... but this is the code
var count = 0;
function cardValue (card) {
var zeroVal = card === 7 || card === 8 || card === 9;
if (zeroVal) return 0;
else if (typeof card === 'string' || card === 10) return -1;
else if (typeof card === 'number' || card !== 10) return 1;
}
function cc(card) {
// Only change code below this line
count += cardValue(card);
if (count > 0) return ${count} Bet
;
else if (count < 0) return ${count} Hold
;
else return ${count} Hold
;
// Only change code above this line
}
nokia6290 sends brownie points to @nicopcat :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for nicopcat
nokia6290 sends brownie points to @nicopcat :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for nicopcat
function testGreaterThan(val) {
if (val >10) { // Change this line
return "Over 100";
}
if (val >5) { // Change this line
return "Over 10";
}
return "10 or Under";
}
// Change this value to test
testGreaterThan(11);
is my code correct i can not pass the challenge can anyone help me please
function cc(card) {
// Only change code below this line
count += cardValue(card);
if (count > 0) return ${count} Bet
;
else if (count < 0) return ${count} Hold
;
else return ${count} Hold
;
// 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'); // 0 Hold
cc(10); cc('J'); cc('Q'); cc('K'); cc('A'); // -5 Hold
@nicopcat
case 2:
case 3:
var count = 0;
function cc(card) {
// Only change code below this line
switch(card) {
case 2:
case 3:
case 4:
case 5:
case 6:
return 5 + " " + "Bet";
case 7:
case 8:
case 9:
return 0 + " " + "Hold";
case 10:
case "J":
case "Q":
case "K":
case "A":
return -5 + " " + "Hold";
case 3:
case 7:
case "Q":
case 8:
case "A":
return -1 + " " + "Hold";
case 2:
case "J":
case 9:
case 2:
case 7:
return 1 + " " + "Bet";
case 3:
case 2:
case "A":
case 10:
case "K":
return -1 + " " + "Hold";
}
// Only change code above this line
}
// Add/remove calls to test your function.
// 提示: Only the last will display
cc(2); cc(3);
function smallestCommons(arr) {
var nums = [],primes = [2,3,5,7], multis = [];
for(var i = Math.min(arr[0],arr[1]); i <= Math.max(arr[0],arr[1]); i++){
if(i != 1){
nums.push(i);
}
}
for(var p = 0; p < primes.length; p){
for(var n = 0; n < nums.length; n++){
/*
check if nums[n] is divisible by primes[p].If true, change value of that
index and set p back to 0(this is to check the new values of 'nums' array)
*/
if((nums[n] % primes[p]) == 0){
nums[n] = nums[n] / primes[p];
p = 0;
/*
Problem: Need to only check if nums[n] is divisible by primes[p] only One times
per num[n] cycles, and not per nums[n] that are divisible by primes[p].
*/
}
//increment p if at last index of nums array
if(n == nums.length-1){
p++;
}
}
}
return multis.concat(nums);
}
console.log(
smallestCommons([1,5])
)
```js
function updateRecords(id, prop, value) {
var obj = collection.id[prop];
console.log(obj);
if(prop != "tracks" && value != ""){
}
return collection;
}
function updateRecords(id, prop, value) {
if(prop != "tracks" && value != ""){
collection.id[prop] = value;
}