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.
inputTrimmed = inputLowercase.replace(/[^a-z0-9]/g,"");
inputTrimmed = inputLowercase.replace(/\s|[,._-]|\050|\051/g,"");
sorry kevinstonge, you can't send brownie points to yourself! :sparkles: :sparkles:
willcodes sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 1923 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
\(
work for matching.
var random = quotes[Math.floor(Math.random() *quotes.length)];
function randomQuote() {
var random = quotes[Math.floor(Math.random() *quotes.length)];
$("#thisquote").text(random.quote);
$("#thisauthor").text("-" +random.author);
};
function changeBackground() {
var random = quotes[Math.floor(Math.random() *quotes.length)];
if ($(quotes[random].author) === "Kramer") {
$("body").css("background-image", "linear-gradient(to top, rgba(0,0,0,0.2), rgba(0,0,0,0.5)),url('file:C:/Users/user/Desktop/freecodecamp/random quote/images/kramer.jpg'");
}
else if (quotes[random].author === "George"){
$("body").css("background-image", "linear-gradient(to top, rgba(0,0,0,0.2), rgba(0,0,0,0.5)),url('file:C:/Users/user/Desktop/freecodecamp/random quote/images/george.jpg'");
}
else if (quotes[random]["author"] === "Elaine"){
$("body").css("background-image", "linear-gradient(to top, rgba(0,0,0,0.2), rgba(0,0,0,0.5)),url('file:C:/Users/user/Desktop/freecodecamp/random quote/images/elaine.jpg'");
}
else if (quotes[random]["author"] === "Jerry"){
$("body").css("background-image", "linear-gradient(to top, rgba(0,0,0,0.2), rgba(0,0,0,0.5)),url('file:C:/Users/user/Desktop/freecodecamp/random quote/images/jerry.jpg'");
}
else{
$("body").css("background-image", "linear-gradient(to top, rgba(0,0,0,0.2), rgba(0,0,0,0.5)),url('file:C:/Users/user/Desktop/freecodecamp/random quote/images/bg.jpg'");
}
};
/* function changeColor() {
var change = colors[Math.floor(Math.random() *colors.length)];
$('body').css("background", change);
$('#getQuote').css("background", change);
};*/
function removeHeader() {
$("#header").remove();
}
$('.btn').click(function() {
removeHeader();
randomQuote();
changeBackground();
});
});
kevinstonge sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 1924 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
function rot13(str) { // LBH QVQ VG!
var string = str.split(" ");
var finished = "";
var map = Array.prototype.map;
var charCodeArray = map.call(str, function (x){
var y = x.charCodeAt(0);
if(y <= 77 && y >= 65){
y = y + 13;
}
else if(y >= 78 && y <= 91){
y = y - 13;}
return y ;
});
for(var i = 0; i<charCodeArray.length; i++){
finished += String.fromCharCode(charCodeArray[i]);
}
return finished;
}
```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
shift
+ enter
provides additional line feeds (space for posting/pasting code).```
function rot13(str) { // LBH QVQ VG!
var string = str.split(" ");
var finished = "";
var map = Array.prototype.map;
var charCodeArray = map.call(str, function (x){
var y = x.charCodeAt(0);
if(y <= 77 && y >= 65){
y = y + 13;
}
else if(y >= 78 && y <= 91){
y = y - 13;}
return y ;
});
for(var i = 0; i<charCodeArray.length; i++){
finished += String.fromCharCode(charCodeArray[i]);
}
return finished;
}
function rot13(str) { // LBH QVQ VG!
var string = str.split(" ");
var finished = "";
var map = Array.prototype.map;
var charCodeArray = map.call(str, function (x){
var y = x.charCodeAt(0);
if(y <= 77 && y >= 65){
y = y + 13;
}
else if(y >= 78 && y <= 91){
y = y - 13;}
return y ;
});
for(var i = 0; i<charCodeArray.length; i++){
finished += String.fromCharCode(charCodeArray[i]);
}
return finished;
}
dexpassenger sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 1925 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
function titleCase(str) {
inputAsArray = str.split(" ");
outputString = "";
for (i=0;i<inputAsArray.length;i++) {
outputString += inputAsArray[i].charAt(0).toUpperCase() + inputAsArray[i].slice(1).toLowerCase() + ((i == inputAsArray.length - 1) ? "" : " ");
}
return outputString;
}
function titleCase(str) {
return str.split(' ').map(function(val) {
return val.charAt(0).toUpperCase() + val.toLowerCase().slice(1);
}).join(' ');
}
function nextInLine(arr, item) {
// Your code here
var res = arr.push(1);
var res1 = arr.shift();
return res1;
}
nextInLine([5,6,7,8,9,10,1],1);
kevinstonge sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:warning: kevinstonge already gave sjames1958gm points
kevinstonge sends brownie points to @bitgrower :sparkles: :thumbsup: :sparkles:
:star2: 1141 | @bitgrower |http://www.freecodecamp.com/bitgrower
ndburrus sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 1926 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
aidenmead sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 1927 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
@sjames1958gm - my code for titleCase(str):
stringAsArray = str.split(" ");
fixedCaseArray = stringAsArray.map(function(val) { return val.charAt(0).toUpperCase() + val.slice(1).toLowerCase(); });
return fixedCaseArray.join(" ");
I wonder if you'd mind commenting on how you know how much to stuff after the word 'return' because I see you put the whole damn function after the word return in your solution! Are there guidelines or rules for that?
johnmica sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1546 | @chrono79 |http://www.freecodecamp.com/chrono79
dueldrawer8 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 1928 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
```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
function isLess(a, b) {
// Fix this code
if (a < b) {
return true;
} else {
return false;
}
}
// Change these values to test
isLess(10, 15);
johnmica sends brownie points to @ndburrus :sparkles: :thumbsup: :sparkles:
:cookie: 988 | @ndburrus |http://www.freecodecamp.com/ndburrus
dueldrawer8 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:warning: dueldrawer8 already gave sjames1958gm points
@rahin1122 Is it this challenge, the one about anti pattern?
if (condition) {
return true;
} else {
return false;
}
can be replaced by
return condition
@sjames1958gm Can you just have a look at my code and could you provide me a solution for this and I am just a new beginner in javascript ..function nextInLine(arr, item) {
// Your code here
var res = arr.push(1);
var res1 = arr.shift();
return res1;
}
nextInLine([5,6,7,8,9,10,1],1);
function largestOfFour(arr) {
var largestOfFourArray = [];
for (i=0;i<arr.length;i++) {
largestOfFourArray.push(arr[i].sort(function(a,b) { return b - a; })[0]);
}
return largestOfFourArray;
}
room for improvement here?
function confirmEnding(str, target) {
return (str.substr(str.length-target.length) === target) ? true : false;
}
return str.substr(-target.length) === target;
true or false is inferred
kevinstonge sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 1547 | @chrono79 |http://www.freecodecamp.com/chrono79
[2, 1]
(a, b) => a - b
2 - 1 == 1
, which is positive
[1, 2]
1 - 2 == -1
let foo = ["bazinga", "bingo", "baz", "quux"];
foo.sort((a, b) => a.length - b.length)
function getIndexToIns(arr, num) {
// Find my place in this sorted array
arr.sort(function(a, b){
return a - b;
});
for(var i = 0; i<arr.length; i++){
if(arr[i] >= num){
return parseInt(i);
}
}
return arr.length;
}
getIndexToIns([1, 2, 3], 15);
function truncateString(str, num) {
return ((str.length <= 3) ? str.slice(0,num) + "..." : (num <=3) ? str.slice(0,num) + "..." : (num >= str.length) ? str : str.slice(0,num-3) + "...");
}
this got ugly!!
function truncateString(str, num) {
return num<str.length ? str.slice(0, num<=3 ? num : num -3)+"..." : str;
}
kevinstonge sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:warning: kevinstonge already gave chrono79 points
str.slice(0,num) + "..."
[1, 2, 3, 4, 5] + {a: 1, b: 2}
// -> '1,2,3,4,5[object Object]'
tracks
property
let object = {a: 1, b: 2, c: 3};
if (!object.hasOwnProperty("tracks")) {
object.tracks = [];
}
object.tracks.push(5);
// -> {a: 1, b: 2, c: 3, tracks: [5]}
object.tracks = []
if (prop === "tracks" && value === "") {
collection[id].tracks = [];
This isn't showing anything in the code window.
var testProp = collection.hasOwnProperty(prop);
console.log ("testProp = " + testProp);
Why is that?
value
is empty, you're supposed to delete the property
function updateRecords(id, prop, value) {
var testProp = collection.hasOwnProperty(prop);
//console.log ("testProp = " + testProp);
if (testProp===false) {
collection[id][prop] = value;
if (prop === "tracks" && value === "") {
//collection[id].tracks = [];
var object = {a: 1, b: 2, c: 3};
//set tracks
if (!object.hasOwnProperty("tracks")) {
object.tracks = [];
}
object.tracks.push(5);
}
} else {
return "WTF!";
}
return collection;
}
if (value !== "" && prop !== "tracks") {
collection[id][prop] = value;
// Write a function which takes:
// an id, a property (prop), and a value.
function updateRecords(id, prop, value) {
// If value is non-blank (value !== "")
// and prop is not "tracks"
// then update or set the value for the prop.
// Your code here
// If the prop is "tracks" and value is non-blank,
// push the value onto the end of the tracks array.
// Your code here
// If value is blank,
// delete that prop.
// Your code here
// Always return the entire collection object.
return collection;
}
function updateRecords(id, prop, value) {
if (value !== "" && prop !== "tracks") {
collection[id][prop] = value;
} else if (prop === "tracks" && value !== "") {
collection[id].tracks.push(value);
} else if (value === "") {
delete collection[id][prop];
}
return collection;
}
is it bad that it took me a half hour to figure this out?
function chunkArrayInGroups(arr, size) {
var j = Math.ceil(arr.length/size - 1);
for(i=0;i<=j;i++) {
arr.splice(i,size,arr.slice(i,i+size));
}
return arr;
}
is there an easier way that I overlooked?
function testLogicalAnd(val) {
// Only change code below this line
if (val <= 50) {
if (val >= 25 ) {
return "Yes";
}
}
// Only change code above this line
return "No";
}
// Change this value to test
testLogicalAnd(24);
Where do I put the && operator
mrblue27 sends brownie points to @kevinstonge :sparkles: :thumbsup: :sparkles:
:cookie: 261 | @kevinstonge |http://www.freecodecamp.com/kevinstonge
in "Escape Sequences in Strings" Assignment I am codding this but it is giving error
var myStr = "FirstLine \n \ SecondLine \ \r ThirdLine"; // Change this line
function updateRecords(id, prop, value) {
if (value !== "" && prop !== "tracks") {
collection[id][prop] = value;
} else if (prop === "tracks" && value !== "") {
collection[id].tracks = [];
collection[id][prop].push(value);
} else if (value === "") {
delete collection[id][prop];
}
return collection;
}
// Alter values below to test your code
updateRecords(2468, "tracks", "Free");
Hey, I'm doing the Global vs. Local scope functions. I'm not sure why my code isn't working:
// Setup
var outerWear = "T-Shirt";
function myOutfit() {
// Only change code below this line
var myOutfit = "sweater";
// Only change code above this line
return outerWear;
}
myOutfit();
Challenge is
Do not change the value of the global outerWear
myOutfit should return "sweater"
Do not change the return statement
if (value !== "") {
if (prop !== "tracks") {
collection[id][prop] = value;
} else if(!collection[id].hasOwnProperty("tracks")) {
collection[id].tracks = [];
collection[id][prop].push(value);
, then paste your code and three more
, then your code will show up in black, like everyone else here - no screen shot needed
```
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
myObj.hasOwnProperty("gift");
return "pony";
}
// Test your code by modifying these values
checkObj("gift");
var myStr = "FirstLine\n\\SecondLine\\\ThirdLine"; // Change this line
thejamiecrawford sends brownie points to @aidenmead :sparkles: :thumbsup: :sparkles:
:cookie: 214 | @aidenmead |http://www.freecodecamp.com/aidenmead
malickarsalan sends brownie points to @jfx1026 :sparkles: :thumbsup: :sparkles:
:cookie: 222 | @jfx1026 |http://www.freecodecamp.com/jfx1026
var myStr = "FirstLine\n\\SecondLine\\\ThirdLine"; // Change this line
var myStr = "FirstLine\n \\\SecondLine\\\ \rThirdLine";
jfx1026 sends brownie points to @aidenmead :sparkles: :thumbsup: :sparkles:
:cookie: 216 | @aidenmead |http://www.freecodecamp.com/aidenmead
function falsy(value) {
if (value === false || value === null || value === 0 || value === undefined || value === "" || value === isNaN) {
return value;
}
}
function bouncer(arr) {
// Don't show a false ID to this bouncer.
return arr.filter(falsy);
}
bouncer([7, "ate", "", false, 9]);
function testLogicalOr(val) {
// Only change code below this line
if (val > 10 || val < 20) {
return "Outside";
}
{
return "Inside";
}
// Only change code above this line
return "Inside";
}
// Change this value to test
testLogicalOr(10);
How do I get the inside to compute. I am only getting the Outside
function bouncer(arr) {
return arr.filter(function(val){return (val===false||val===""||val===null||val===0||val===undefined) ? false : true; });
}
var myStr = "FirstLine\n\\SecondLine\\\ThirdLine"; // Change this line
and var myStr="FirstLine\n\\SecondLine\\\rThirdLine";
kevinstonge sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star2: 1281 | @qualitymanifest |http://www.freecodecamp.com/qualitymanifest
function bouncer(arr) {
return arr.filter(function(val){return (val); });
}
arguments
object again on this one, and you don't want to convert it to a string
function testLogicalOr(val) {
// Only change code below this line
if (val > 10 || val < 20) {
return "Outside";
}
// Only change code above this line
return "Inside";
}
// Change this value to test
testLogicalOr(25);
How do I return the "Inside"val
is > 10
AND <20
?
||
(OR operator) into &&
(AND operator)
testLogicalOr(25)
?
@qualitymanifest Here's what's up:
I'm currently on the Validate Us Numbers challenge
https://www.freecodecamp.com/challenges/validate-us-telephone-numbers
I'm aware that there's a bunch of RegExp challenges that I already passed, though I used some obscure long If-Else chains that checks for each value of the string. I guess this is the perfect challenge for me to really learn RegExp.
Would you mind guiding me step by step on what should I do in this challenge?
here:
Allow a 1 and a space, then area code with BOTH parens or NO parens, then allow a space/dash, three more numbers, allow another space/dash, then the last four numbers. Nothing before or after
kirbyedy sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star2: 1282 | @qualitymanifest |http://www.freecodecamp.com/qualitymanifest
string
?
alchermd sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star2: 1283 | @qualitymanifest |http://www.freecodecamp.com/qualitymanifest
regex goes here.test(str)
var globalArguments = [];
function destroyer(arr) {
globalArguments[0] = arguments[1];
globalArguments[1] = arguments[2];
globalArguments[2] = arguments[3];
return arr.filter(function destroyFilter(val){return (val===globalArguments[0]||val===globalArguments[1]||(globalArguments[2]&&val===globalArguments[2])) ? false : true;});
}
in
method of Array to check if val
is in globalArguments
to shorten your code.
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var array = [];
array = arguments[0];
array.push(num);
array.sort(function sortArr(a, b)
{
return a - b;
});
return array.indexOf(num);
}
getIndexToIns([40, 60], 50);
filter
function, right?
arr
which is passed into the function
function destroyer(arr) {
globalArguments = arguments;
return arr.filter(function(val){return (val===globalArguments[1]||val===globalArguments[2]||val===globalArguments[3]) ? false : true;});
}
this looks a bit better ... thanks @lx-t ... but could one of you share your code for Seek and Destroy? I'm not really confident that this is the best way.
kevinstonge sends brownie points to @lx-t :sparkles: :thumbsup: :sparkles:
:cookie: 439 | @lx-t |http://www.freecodecamp.com/lx-t
arr
). then run a filter on arr
, removing the pieces of arr that are present (indexOf !== -1) in your newly made arguments array
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.push(num);
arr.sort(function sortArr(a, b)
{
return a - b;
});
return arrindexOf(num);
}
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.push(num);
arr.sort(function sortArr(a, b)
{
return a - b;
});
return arr.indexOf(num);
}
jod29 sends brownie points to @faisal1337 :sparkles: :thumbsup: :sparkles:
:cookie: 271 | @faisal1337 |http://www.freecodecamp.com/faisal1337
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(4, 1);
neliusknight sends brownie points to @cal-culator :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for cal-culator
qualitymanifest sends brownie points to @lx-t :sparkles: :thumbsup: :sparkles:
:cookie: 440 | @lx-t |http://www.freecodecamp.com/lx-t
(piece of arr.indexOf(additional element array) === -1
kevinstonge sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star2: 1284 | @qualitymanifest |http://www.freecodecamp.com/qualitymanifest
function destroyer(arr) {
globalArguments = arguments;
return arr.filter(function(val){return Array.from(globalArguments).indexOf(val) === -1;});
}
cal-culator sends brownie points to @qualitymanifest :sparkles: :thumbsup: :sparkles:
:star2: 1285 | @qualitymanifest |http://www.freecodecamp.com/qualitymanifest
var
in front of it, and if you made it an Array at the same time as you assigned it, it wouldn't have to make a new Array on each iteration of the filter, so would be a little more efficient
var globalArguments = arguments;
doesn't that already make it an array since arguments is an array?
1: "I", 4: "IV"
etc. but you're trying to make an object by wrapping it in [] when you should be wrapping it in {}. also, i think this one is just easier with arrays rather than objects
var globalArguments = Array.from(arguments)
arguments
is an array-like object (has numeric properties and .length property), but no array methods.
chaitanyaashtekar sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2192 | @blauelf |http://www.freecodecamp.com/blauelf
"0",
"1"
etc and .length property). So .call() allows calling array methods on array-like objects like strings (string wrappers are array-like), arguments objects, nodelists, etc. Also on your own array-like objects.
var x =new Boolean("null"); //I understand
if (x) console.log(1);
var y =new Boolean(null); //should'nt execute
if (y)console.log(2); //but does.why ??
how do I know when I can chain methods and when I can't?
For example this works:
arr.sort().indexOf(n);
but this doesn't work:
arr.push(i).indexOf(n);
if
coerces values to Boolean type, so all objects coerce to true.
arr.push(i)
doesnt return an array
kevinstonge sends brownie points to @chaitanyaashtekar :sparkles: :thumbsup: :sparkles:
:cookie: 383 | @chaitanyaashtekar |http://www.freecodecamp.com/chaitanyaashtekar
Boolean
rather than new Boolean
Boolean(val)
.
.concat
but that won't modify the array in place like .push
does
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement
[1, 2, 3, 4].concat(5).indexOf(5);
@kevinstonge
function palindrome(str) {
// Good luck!
var a=str.toLowerCase().replace(/[^A-Z0-9]+/ig, "").split("");
var b=str.toLowerCase().replace(/[^A-Z0-9]+/ig, "").split("").reverse("");
for (var i=0; i<a.length;i++){
if (a[i]===b[i]){
return true;
}
else if (a[i]!==b[i]){
return false;
}
}
}
palindrome("almostomla");
why doesn't this code work for "almostomla"?
chaitanyaashtekar sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2129 | @masd925 |http://www.freecodecamp.com/masd925
y
isn't false
chaitanyaashtekar sends brownie points to @llamatarianism :sparkles: :thumbsup: :sparkles:
:star2: 1010 | @llamatarianism |http://www.freecodecamp.com/llamatarianism
kevinstonge sends brownie points to @llamatarianism :sparkles: :thumbsup: :sparkles:
:star2: 1011 | @llamatarianism |http://www.freecodecamp.com/llamatarianism
return == break
true
when char are equal.let the loop continue.return false only when you find them not equal
@Cal-culator ```
for (var i=0; i<a.length;i++){
if (a[i]!==b[i]){
return false;
}
```
.join
to make a
and b
into strings
@Cal-culator ```
for (var i=0; i<a.length;i++){
if (a[i]!==b[i]){
return false;
}
```
@chaitanyaashtekar thanks
@llamatarianism thanks
```
function palindrome(str) {
// Good luck!
var a=str.toLowerCase().replace(/[^A-Z0-9]+/ig, "").split("");
var b=str.toLowerCase().replace(/[^A-Z0-9]+/ig, "").split("").reverse("");
for (var i=0; i<a.length;i++){
if (a[i]===b[i]){
}
else if (a[i]!==b[i]){
return false; break;
}
}
return true;
}
palindrome("almostomla");
cal-culator sends brownie points to @chaitanyaashtekar and @llamatarianism :sparkles: :thumbsup: :sparkles:
:star2: 1012 | @llamatarianism |http://www.freecodecamp.com/llamatarianism
:cookie: 384 | @chaitanyaashtekar |http://www.freecodecamp.com/chaitanyaashtekar
====
function palindrome(str) {
// Good luck!
var a=str.toLowerCase().replace(/[^A-Z0-9]+/ig, "").split("");
var b=str.toLowerCase().replace(/[^A-Z0-9]+/ig, "").split("").reverse("");
for (var i=0; i<a.length;i++){
if (a[i]===b[i]){
}
else if (a[i]!==b[i]){
return false; break;
}
}
return true;
}
palindrome("almostomla");
I just changed it to that
return a===b
no need of for loop
[1, 2, 3] !== [1, 2, 3]
because they're different objects
.join
them later.i didnt read correctly
:warning: chaitanyaashtekar already gave llamatarianism points
chaitanyaashtekar sends brownie points to @llamatarianism :sparkles: :thumbsup: :sparkles:
Hello folks.
I'm trying to understand, 'Nesting for loops'. I got a working solution, but I don't understand what 'j' is doing.
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
var array = [arr];
for (var i=0; i < arr.length; i++){
for (var j=0; j < arr[i].length; j++){
product = product * arr[i][j];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
It looks like 'j' is checking the length of the container array and then moving to the next item. However, how is it moving in and out of each of the nested arrays [0], [1] and [2]?
arr[i]
is one subarray and j loop loops through its indices.
TypeError: str.toUpperCase.split is not a function. (In 'str.toUpperCase.split(" ")', 'str.toUpperCase.split' is undefined)
How do i fix this?
.toUpperCase().split()
cal-culator sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2130 | @masd925 |http://www.freecodecamp.com/masd925
ReferenceError: keys is not defined
while using sourceKeys = Object.keys(source);
. Can anyone tell me why?
function whatIsInAName(collection, source) {
// What's in a name?
var arr = [];
// Only change code below this line
// There was a for loop involved. The first part involved getting the keys from the source
sourceKeys = Object.keys(source);
return collection.filter(function (obj){
for(var i = 0; i < keys.length;i++){
if(!obj.hasOwnProperty(sourceKeys[i]) || obj[sourceKeys[i]] !== source[sourceKeys[i]]) {
return false;
}
}
return true;
});
}
// Only change code above this line
kamilmalek sends brownie points to @athaman :sparkles: :thumbsup: :sparkles:
:cookie: 605 | @athaman |http://www.freecodecamp.com/athaman
leebut sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 2131 | @masd925 |http://www.freecodecamp.com/masd925
function titleCase(str) {
var a= str.split(" ");
var b=[];
var c=[];
var d=[];
for (var i=0;i<a.length;i++){
b=a[i].split("");
b[0].toUpperCase();
c.push(b[0]);
d= c.join("").toUpperCase().split("");
b[0].replace(d[i]);
a[0].replace(d[i]);
a[i].join("");
}
a.join(" ")
console.log(a);
}
titleCase("I'm a little tea pot");
this is the code
'appleboycat'
, but you can define the delimiter as you like.
function repeat(str, num) {
// repeat after me
if(num<0){
return "";
}
else {
var strs = "";
for(var i=0;i<num;i++){
strs +=str;
}
return '"'+strs+'"';
}
}
repeat("abc", 1);
jiajinning sends brownie points to @ekleung123 :sparkles: :thumbsup: :sparkles:
:cookie: 101 | @ekleung123 |http://www.freecodecamp.com/ekleung123
function titleCase(str) {
var a= str.split(" ");
var b=[];
var c=[];
var d=[];
var e="";
var f=[];
for (var i=0;i<a.length;i++){
b=a[i].split("");
d= c.join("").toUpperCase().split("");
b[0]=d[i];
a[i]= b.join("");
}
a.join(" ");
console.log(a);
}
titleCase("I'm a little tea pot");
I tried doing this
str.toLowerCase().split(" ")
(to remove uppercase letters within words), also, you don't return the result of a.join(" ")
(it won't change a but return a string, which you currently ignore)
a.join(" ")
?
@Cal-culator
function titleCase(str) {
var a = str.split(" ");
var b = [];
for (var i=0; i<a.length; i++) {
b.push(a[i].charAt(0).toUpperCase());
}
return b;
}
var y = titleCase("I'm a little tea pot");
console.log(y);
vmohan9 sends brownie points to @benalron :sparkles: :thumbsup: :sparkles:
:cookie: 373 | @benalron |http://www.freecodecamp.com/benalron
function destroyer(arr) {
// Remove all the values
var args =arr.slice.call(arguments);
for (var i = 0;i<args.length;i++)
{
if (arr[i] == args[i])
{
return arr;
}
}
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
@Cal-culator
function titleCase(str) {
var a = str.split(" "), b = [];
for (var i=0; i<a.length; i++) {
var x = a[i]
x = x.charAt(0).toUpperCase() + a[i].slice(1,a.length+1);
b.push(x);
}
return b
}
var y = titleCase("I'm a little tea pot");
console.log(y); // yields "I'm A Little Tea Pot"
function titleCase(str) {
var a=str.toLowerCase().split(" ");
var b=[];
var c=[];
var d="";
var e=[];
var f=[];
var g=[];
for (var i=0; i<a.length;i++){
b=a[i].split("");
console.log(b);
c.push(b[0]);
console.log(c);
d = c.join("").toUpperCase();
console.log(d);
e= d.split("");
console.log(e);
b[0]=e[i];
f=b.join("");
console.log(f);
g.push(f);
}
return g.join(" ");
}
titleCase("I'm a little tea pot");
Ignore the console.log();
cal-culator sends brownie points to @ekleung123 :sparkles: :thumbsup: :sparkles:
:cookie: 102 | @ekleung123 |http://www.freecodecamp.com/ekleung123
function destroyer(arr) {
// Remove all the values
var basearr = arr[0];
var arglength = arguments.length;
var newarray = [];
for (var i = 1; i < arglength; i++) {
newarray.push(arguments[i]);
}
console.log(newarray);
var finalarray = arguments[0].filter(function(elem, index, array) {
elem = false;
for (i = 0; i < newarray.length; i++) {
if (newarray[1] !== elem) {
elem = true;
}
}
return elem;
});
arr = finalarray
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
if (contacts.firstName !== firstName){
return "No such contact";}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
leebut sends brownie points to @kevinstonge :sparkles: :thumbsup: :sparkles:
@faisal1337
var args =arr.slice.call(arguments);
function destroyer(arr) {
// Remove all the values
}
function consta(arr)
{
for (var i = 0 ; i<arr.length;i++)
{
if (arr[i] == args[i])
{
}
}
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
what i need to put in the if conditions in consta()
`
js
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$("#data").html("a" + position.coords.latitude + "<br>longitude: " + position.coords.longitude);});
};
})
leebut sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2193 | @blauelf |http://www.freecodecamp.com/blauelf
@faisal1337
function destroyer(arr) {
// Remove all the values
var args =arr.slice.call(arguments);
function consta(args)
{
for (var i = 0 ; i<arr.length;i++)
{
if (arr[i] == args[i])
{
}
}
}
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
@Blauelf is it okay? and when i am returning anything in consta() it does not return what is the issue here?
faisal1337 sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2194 | @blauelf |http://www.freecodecamp.com/blauelf
undefined
. Also, you never use consta. Oh, and consta would implicitly return undefined
in all cases, too.
args
, since this shadows the variable in the outer scope.
Hi, can you please help me with my code var Bike = function() {
// Only change code below this line.
this.getGear = function(change) {
return change;
};
this.setGear = function(change) {
return change;
};
};
var myCar = new Car();
var myBike = new Bike();
myBike.setGear(4);
```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
function chunk(arr, size) {<br> // Break it up.<br> var arr1 = [];<br> var arr2 = [];<br> for(var i=0; i<arr.length; ){<br> for(var j=0; j<size; j++,i++){<br> arr2[j] = arr[i];<br> }<br> arr1.push(arr2);<br> }<br> return arr1;<br>}<br><br>chunk(["a", "b", "c", "d"], 2);<br>
unction chunk(arr, size) {
// Break it up.
var arr1 = [];
var arr2 = [];
for(var i=0; i<arr.length; ){
for(var j=0; j<size; j++,i++){
arr2[j] = arr[i];
}
arr1.push(arr2);
}
return arr1;
}
chunk(["a", "b", "c", "d"], 2);
@hnsxxscyx You might want to move the var arr2 = [];
inside the outer loop, before the inner loop. This way you get a fresh array for each iteration of the outer loop.
And maybe you need a check like j<size && i<arr.length
instead of just j<size
for not including undefined
s when arr.length is not a multiple of size.
@faisal1337 @Blauelf
function destroyer(arr) {
// Remove all the values
var args =arr.slice.call(arguments);
function consta()
{
var max = [2,3];
for (var i = 0 ; i<arr.length;i++)
{
if (arr[i] == max[i])
{
return true;
}
}
return false;
}
var new_array ;
for (var i = 0;i<arr.length;i++)
{
new_array= arr.filter(consta);
}
return new_array;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I have harcoded [2,3] in max for the time being later on i'll work on that but why is still it is being tangled?
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
if (contacts[i].firstName !== firstName){
return "No such contact";}
else if (contacts[i] !== prop){
return "No such property";
}
for (var j = 0; j < contacts[i].length; j++){
return contacts[i], [prop][j];
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
hnsxxscyx sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2195 | @blauelf |http://www.freecodecamp.com/blauelf
@Blauelf
function destroyer(arr) {
// Remove all the values
var args =arr.slice.call(arguments);
function consta()
{
var max = [2,3];
for (var i = 0 ; i<arr.length;i++)
{
if (arr[i] == max[i])
{
return true;
}
}
return false;
}
var new_array ;
for (var i = 0;i<arr.length;i++)
{
new_array= arr.filter(consta);
}
return new_array;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I have hardcoded [2,3] for the time being but i am still left with an empty array when i return new_array? where am i wrong?
@MohammadHasham consta should take one argument, a value, You should then iterate args (ignoring the first element, as this is equal to arr
), and compare the args element to the passed value. On match, return false, after the loop return true.
And no need for another loop in destroyer if you are going to use filter.
function chunk(arr, size) {
// Break it up.
var array = [];
for(var i=0; i<arr.length; i++){
array[i] = arr[i];
}
for(i=0,h=0; h<arr.length; i++,h++){
for(var j=0; j<size; j++){
array[i][h] = arr[h];
}
}
//arr = array;
return array;
}
chunk(["a", "b", "c", "d"], 2);
size
times. Also, you try to access properties of numbers (array contains numbers, you try to use them as arrays)
function destroyer(arr) {
// Remove all the values
var args =arr.slice.call(arguments);
function consta()
{
var max = [2,3];
for (var i = 0 ; i<arr.length;i++)
{
for (var j=0;j<max.length;j++)
{
if (arr[i] == max[j])
{
return true;
}
}
}
return false;
}
new_array= arr.filter(consta);
return new_array;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
There's little use in a function passed to filter if it does not take at least one argument.
Filter will call it with three arguments (the current element, its index in the array, and the array itself), and the function will ignore all of them.
function lookUpProfile(firstName, prop){
// Only change code below this line
for (i = 0; i < contacts.length; i++){
if (contacts.firstName === firstName){
for (var j = 0; j < contacts[i]; j++){
if (contacts[i] === prop){
return contacts[i][firstName] + contacts[i][prop][j];
}
}
}
}
// Only change code above this line
}
contacts[i].firstName
, not contacts.firstName
leebut sends brownie points to @blauelf and @kevinstonge :sparkles: :thumbsup: :sparkles:
:warning: leebut already gave kevinstonge points
:warning: leebut already gave blauelf points
var getResults = function(){
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
$.getJSON('https://api.twitch.tv/kraken/channels/OgamingSC2/?callback=?', function(data1) {
$.getJSON('https://api.twitch.tv/kraken/streams/OgamingSC2/?callback=?',function(data2){
console.log(data1);
console.log(data2);
});
});
}
function Streamer(resultStream,resultChannel){
this.name = resultChannel.display_name;
this.image = resultChannel.game + ": " + resultChannel.logo;
this.description = resultChannel.status;
this.online = (resultStream.stream != null);
console.log(resultStream);
console.log(resultChannel);
}
var getResults = function(){
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
$.getJSON('https://api.twitch.tv/kraken/channels/OgamingSC2/?callback=?', function(data1) {
$.getJSON('https://api.twitch.tv/kraken/streams/OgamingSC2/?callback=?',function(data2){
console.log(data1);
console.log(data2);
var streamer = new Streamer(data1,data2);
console.log(streamer);
});
});
}
var array = [4,5,6,7,8];
var singleVal = 0;
// Only change code below this line.
var singleVal = array.reduce(function(singleVal, el){
return singleVal + el;
});
//singleVal = array;
@Blauelf
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments);
args.splice(0,1);
return arr.filter(consta);
function consta(element)
{
return args.indexOf(element) == -1;
}
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
How does the return args.indexOf ... is acting ?
var array = [4,5,6,7,8];
//var singleVal = 0;
// Only change code below this line.
var singleVal = array.reduce(function(singleVal, el){
return singleVal + el;
}, 0);
//singleVal = array;
arr.filter
, it is an element of arr.
victorso sends brownie points to @wo1v3r :sparkles: :thumbsup: :sparkles:
:cookie: 283 | @wo1v3r |http://www.freecodecamp.com/wo1v3r
function titleCase(str) {
str=str.toLowerCase();
var word;
var i=0;
var position=0;
var np=0;
var long;
word=str.split(' ');
str=str.split('');
str[0]=str[0].toUpperCase();
//return str;
for(i=0;i<30;i++){
long=word[i].length;
np=position+long+1+np;
str[np].toUpperCase();
}
str=str.join();
//return str;
}
Could any one help with the error inside for loop?
the compiler keep saying cannot read property 'toUpperCase' of underfined and cannot read property 'length' of underfined
@andrew45655
` ```` ` ```` `
javascript
[code goes here]
` ```` ` ```` `
formats to:
code goes here
mohammadhasham sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 2196 | @blauelf |http://www.freecodecamp.com/blauelf
@Wo1v3r
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var x = arr.concat(num);
var c = x.sort();
return c;
//return c.indexOf(num);
}
getIndexToIns([5, 3, 20, 3], 5);
why is it not sorting correctly?
mohammadhasham sends brownie points to @athaman and @wo1v3r and @bkinahan :sparkles: :thumbsup: :sparkles:
:cookie: 284 | @wo1v3r |http://www.freecodecamp.com/wo1v3r
:cookie: 606 | @athaman |http://www.freecodecamp.com/athaman
:star2: 2003 | @bkinahan |http://www.freecodecamp.com/bkinahan
puven12 sends brownie points to @wo1v3r :sparkles: :thumbsup: :sparkles:
:cookie: 285 | @wo1v3r |http://www.freecodecamp.com/wo1v3r
Could someone potentially help me figure out what i'm doing wrong?
My code is:
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(i = 1; i < arr.length; i++) {
for(n = 1; n < arr[i].length; n++) {
return product * arr[i][n];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
When i want to make first letter of each word to upper case, I get error touppercase undefined and 'length' underfined
javascript
[function titleCase(str) {
str=str.toLowerCase(); //lower case all words
var word;
var i=0;
var position=0;
var np=0;
var long;
word=str.split(' '); //split to words
str=str.split(''); //split to letters
str[0]=str[0].toUpperCase(); //upper case the first letter
//return str;
for(i=0;i<30;i++){
long=word[i].length; //get length of words
np=position+long+1+np; //update position of words
str[np].toUpperCase(); //change target word to uppre case
}
str=str.join();
return str;
}]
function sumAll(arr) {
var min = Math.min.apply(Math,arr);
var max= Math.max.apply(Math,arr);
var number = [];
var final = 0;
for (var i = min+1; i < max; i++) {
number.push(i);
}
var result = number.map(function(bam){
final += bam;
});
return final + max + min;
}
sumAll([5, 10]);
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(i = 1; i < arr.length; i++) {
for(n = 1; n < arr[i].length; n++) {
product = product * arr[i][n];
}
}
// Only change code above this line
return product;
}
Math.max(arr[0],arr[1])
instead of using apply
@BKinahan
function rot13(str) { // LBH QVQ VG!
var s;
s = str.charCodeAt(0+13);
return str.fromCharCode(s);
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Why is fromCharCode() giving an error?
```function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(i = 1; i < arr.length; i++) {
for(n = 1; n < arr[i].length; n++) {
product * arr[i][n];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);```
.fromCharCode
is called on String
, not just any string
1
for i
and n
will cause problems. arrays indices start at 0
sleepy-guy sends brownie points to @juicedrinker :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for juicedrinker
defeds sends brownie points to @bkinahan and @juicedrinker :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for juicedrinker
:star2: 2004 | @bkinahan |http://www.freecodecamp.com/bkinahan
$.getJSON("http://quotes.stormconsultancy.co.uk/random.json?callback=?", function(data) {
console.log(data);
});
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat='+position.coords.latitude+'&lon='+position.coords.longitude+'&appid=833dc2ccd1bb85729f4b968468cc1ad5', function(json){
$("#data").html(JSON.stringify(json))});
});
};
})
$("#data").html(JSON.stringify(json))Math.max(...arr)
Object {
author: "E. W. Dijkstra",
id: 15,
permalink: "http://quotes.stormconsultancy.co.uk/quotes/15",
quote: "It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration."
}