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.
hypercuber sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:warning: hypercuber already gave cmccormack points
function findLongestWord(str) {
var index = 0;
var test;
var arr = str.split(" ");
for(i=0;i<arr.length;i++){
test = arr[i].length;}
if (index<test){
index = arr[i].length;
}
return index;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
:point_up:
This is what your code actually looks like with proper indentation (and that closing bracket on a separate line). :point_down:
function findLongestWord(str) {
var index = 0;
var test;
var arr = str.split(" ");
for(i=0;i<arr.length;i++){
test = arr[i].length;
}
if (index<test){
index = arr[i].length;
}
return index;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
dyon3334 sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 585 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
yeah. First time I did that challenge, assumed from function name that wanted the word. :p
Easy fix, but very reasonable assumption based on function name
request.onload = function () {
/* body... */
var Recieved = request.response;
var GoogleApi = JSON.parse(Recieved);
}
kumquatfelafel sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 3571 | @moigithub |http://www.freecodecamp.com/moigithub
var requestURL = 'https://maps.googleapis.com/maps/api/geocode/json?address=" + Concat + "&key=AIzaSyBCyqeNvQ2ykQl524BcIWr_XAJwApEyWZU'
var request = new XMLHttpRequest();
var GoogleApi;
function StoreObj() {
var UsrObjects = {
Name : FirstName.value,
email: EmailAddress.value,
destination_Country : DestinationCountry.value,
destination_State : DestinationState.value,
};
localStorage.setItem('StoredUsrObj', JSON.stringify(UsrObjects));
//The dissappering act for the div 'PostContainer'
$('.PostContainer').fadeOut("slow", function() {
// Callback is empty
});
request.open('GET',requestURL);
request.responseType = 'json';
request.send();
}
request.onload = function () {
/* body... */
var Recieved = request.response;
GoogleApi = JSON.parse(Recieved);
}
[object object]
big-jo sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8277 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
I saw this and was just confused on how to get out the location under geometry, can anyone help out?
.results["0"].geometry.location
.results["0"].geometry.location.lat
.results["0"].geometry.location.lng
big-jo sends brownie points to @longnt80 :sparkles: :thumbsup: :sparkles:
:cookie: 485 | @longnt80 |http://www.freecodecamp.com/longnt80
function mutation(arr) {
for (i = 0; i < arr[1].length; i++) {
if(arr[i].toLowerCase() === 'scatter the floor');
}
}
mutation(["hello", "hey"]);
i
have on, e.g., the final iteration of for loop?var i = 0
instead. Without that, i
is treated as a global variable, which at best provides no benefit and at worst could result in your program breaking somewhere.
Hi everyone!
I am trying to solve the palindrome problem from the basic algorithm section.
Here is my code:
function palindrome(str) {
// Good luck!
var converted = str.replace(/\d*[\W_]+/gi, '');
var toLow = converted.toLowerCase();
var splitted = toLow.split("");
var reversed = splitted.reverse();
var concatted = reversed.join('');
if (concatted === toLow) {
return true;
} else {
return false;
}
// return toLow;
}
palindrome("1 eye for of 1 eye.");
Now, this is working just fine on my eye, but it can't pass the test because as the editor saying:
palindrome("1 eye for of 1 eye.") should return false.
But, is it really? I think IT IS a palindrome and hence it should return true
Can anyone tell me where I am wrong?
1 eye for of 1 eye
becomes eeyeforofeye
when you remove all the numbers, spaces and symbol. And then its a palindrome, isn't it? :/
eyeforofeye
is same even when you spell backword
Good point @gothamknight
It says: Note
You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.
Maybe I need to keep the number.
Let me try
faahim sends brownie points to @gothamknight and @heroiczero :sparkles: :thumbsup: :sparkles:
:cookie: 363 | @gothamknight |http://www.freecodecamp.com/gothamknight
:star2: 1590 | @heroiczero |http://www.freecodecamp.com/heroiczero
@faahim This:
if (concatted === toLow) {
return true;
} else {
return false;
}
Should just be...return concatted === toLow;
faahim sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:star2: 4419 | @revisualize |http://www.freecodecamp.com/revisualize
faahim sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:warning: faahim already gave revisualize points
Method chaining?
Never heard about it!
anyone have an alternative solution for this challenge: https://www.freecodecamp.org/challenges/sum-all-numbers-in-a-range ?
I was trying to do this as FP as possible:
function sumAll(arr) {
return (([min, max]) =>
Array.from(Array(max - min + 1).keys())
.map(i => i + min)
.reduce((sum, n) => sum + n)
)([
...arr.sort((a, b) => a - b)
])
}
sumAll([1, 4]);
@bitcoinabdi
GitHub Pages
Note: this feature is available with react-scripts@0.2.0 and higher.
Step 1: Add homepage to package.json
The step below is important!
If you skip it, your app will not deploy correctly.
Open your package.json and add a homepage field:
"homepage": "https://myusername.github.io/my-app",
Create React App uses the homepage field to determine the root URL in the built HTML file.
Step 2: Install gh-pages and add deploy to scripts in package.json
Now, whenever you run npm run build, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
To publish it at https://myusername.github.io/my-app, run:
npm install --save gh-pages
Alternatively you may use yarn:
yarn add gh-pages
Add the following scripts in your package.json:
"scripts": {
Step 3: Deploy the site by running npm run deploy
Then run:
npm run deploy
Step 4: Ensure your project’s settings use gh-pages
Finally, make sure GitHub Pages option in your GitHub project settings is set to use the gh-pages branch:
gh-pages branch setting
faahim sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:warning: faahim already gave revisualize points
npm run deploy
updates the gh-pages branch
yee! Done!
Number was the issue! :)
(Math.max(...arr)*(Math.max(...arr)+1) / 2) - (Math.min(...arr)*(Math.min(...arr)-1) / 2)
So, @revisualize
Is there any place where I can enter my regex to see what it means?
Sure I can look up, but it's better if there's a site for that
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
//create new find Index function return index or -1
function findElInArray(array, seekEl, zeroOrFirst){
var result = -1;
for(var i = 0; i< array.length;i++){
if(array[i][zeroOrFirst]==seekEl){
result = i;
}
}
return result;
}
//clone arr1 and 2
var arr1Clone= arr1.slice();
var arr2Clone= arr2.slice();
//fill and sort combinedArray
var combinedArray = [];
for(var j=0;j<arr1.length;j++){
arr1[j].shift();
if(findElInArray(combinedArray, arr1[j][0],0==-1)){
combinedArray.push(arr1[j]);
}
}
for(var k=0;k<arr2.length;k++){
arr2[k].shift();
if(findElInArray(combinedArray, arr2[k][0],0)==-1){
combinedArray.push(arr2[k]);
}
}
combinedArray.sort();
return arr1Clone;
}
Hi, i was trying to clone the arr1 and arr2 on code below but failed, tried to use const but it is not supported by the platform, any idea how to really copy arr1 and 2 ?
max*(max+1)/2 - (min-1)*(min)/2 ?
@revisualize I'm stalking a little bit on you! :P
I see you kept all your fcc code on your GitHub. Doesn't FCC stores your code at your profile?
I mean, Is that something I should do too?
combinedArray.sort();
namethatisnottaken sends brownie points to @manish-giri :sparkles: :thumbsup: :sparkles:
:star2: 6387 | @manish-giri |http://www.freecodecamp.com/manish-giri
@revisualize I saw your solution on github
const sumAll = ([x, y]) => (x + y) * (Math.abs(x - y) + 1) / 2;
:+1:
Oh Okay, That's fine. @revisualize
I was just asking about how far you've gotten in your learning journey.
I'm just starting, I'd ask you what book would you recommend or what resource you've found useful (beside fcc)
faahim sends brownie points to @revisualize :sparkles: :thumbsup: :sparkles:
:warning: faahim already gave revisualize points
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
//create new find Index function return index or -1
function findElInArray(array, seekEl, zeroOrFirst){
var result = -1;
for(var i = 0; i< array.length;i++){
if(array[i][zeroOrFirst]==seekEl){
result = i;
}
}
return result;
}
//fill and sort combinedArray
var combinedArray = [];
for(var j=0;j<arr1.length;j++){
arr1[j].shift();
if(findElInArray(combinedArray, arr1[j][0],0==-1)){
combinedArray.push(arr1[j]);
}
}
for(var k=0;k<arr2.length;k++){
arr2[k].shift();
if(findElInArray(combinedArray, arr2[k][0],0)==-1){
combinedArray.push(arr2[k]);
}
}
combinedArray.sort();
return arr;
}
namethatisnottaken sends brownie points to @manish-giri and @revisualize :sparkles: :thumbsup: :sparkles:
:warning: namethatisnottaken already gave manish-giri points
:star2: 4420 | @revisualize |http://www.freecodecamp.com/revisualize
Object.keys()
[['key', 'value'], [],...]
.filter()
to Object.entries()
.map()
map
over Object.entries
let obj = {'a': 1, 'b':2};
[['a', 1], ['b', 2]]
Object.entries(obj)
let keys = [];
for (var prop in object) {
if(!keys.includes(prop) {
keys.push(prop)
}
}
if(!keys.includes(prop) {
keys.push(prop)
for...in
loop iterates the keys of enumerable (~not built-in) properties of the object and prototype chain. There are no inherited enumerable properties on plain objects so that for...in
loop just iterates the property keys of that object.
for(var i = 0; i < array.length; i++)
Object.keys(obj)
would not look up the prototype chain, so would be a bit more logical, but both work.
junipberry sends brownie points to @manish-giri and @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4393 | @masd925 |http://www.freecodecamp.com/masd925
:star2: 6389 | @manish-giri |http://www.freecodecamp.com/manish-giri
function destroyer(arr) {
// 请把你的代码写在这里
return arr.filter(function(val) {
for(var i=1; i<arguments.length; i++) {
if(val === arguments[i])
return false;
}
return true;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
arguments
object.
function getKeys(obj){
var myArr = [];
for (var i in obj){
if (obj.hasOwnProperty(i)){
myArr.push(obj[i]);
}
}
}
i
loops the property keys of the object, and there cannot be duplicates, so no need for that check.
function getAllKeys(obj) {
let keys = [];
for (var prop in obj) {
keys.push(prop);
}
}
prop
will be each property key (a string) in its turn.
prop
, and values with obj[prop]
if you need them.
function getKeys(obj){
var myArr = [];
for (var prop in obj){
myArr.push(prop);
}
return myArr;
}
junipberry sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4394 | @masd925 |http://www.freecodecamp.com/masd925
myArr[myArr.length] = prop;
for...in
loop is restricted too, you need to wait for the full moon and find a sage.
Number.isInteger()
. Then calculate the square and push the result into a result array. You can also use methods like filter
and map
if you like.
for...in
loop or iterate Object.keys(obj)
(or use some similar ES6 method). If you wan't to loop objects property keys, you need to use the object.
let arr = realNumberArray.filter(Number.isInterger(realNumberArray)) => arr.push();
var squaredIntegers = realNumberArray.map(arr);
You're also not using arrow properly.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
if (multiplayer) {
// i === row
// j === column
if(turn==="0"){
markToPlace = "X";
}else{
markToPlace = "0";
}
$('.col').click(function() {
var i = $(this).data('i');
var j = $(this).data('j');
if (entrys[i][j] === '') {
$(this).html(markToPlace);
entrys[i][j] = markToPlace;
var gameState = gameOver(entrys);
if (gameState) {
alert('game over ' + gameState + ' won');
return;
}
}
});
}
function translatePigLatin(str) {
var vowels = ["a","e","i","o","u"];
var arr = str.split("");
if (vowels.indexOf(arr[0]) == -1) {
arr = arr.join("").slice(1) + arr.slice(0,1) + ("ay");
return arr;
}
else {
arr.push("way");
return arr.join("");
}
}
translatePigLatin("algorithm");
That's entirely possible, like
if (vowels.indexOf(str[0]) !== -1) {
return str + "way";
}
for (var i = 1; i < str.length; i++) {
if (vowels.indexOf(str[i]) !== -1) {
break;
}
}
return str.slice(i) + str.slice(0, i) + "ay";
or
if (vowels.indexOf(str[0]) !== -1) {
return str + "way";
}
for (var i = 1; i < str.length && vowels.indexOf(str[i]) === -1; i++) {
// nothing to do
}
return str.slice(i) + str.slice(0, i) + "ay";
i < str.length
and vowels.indexOf(str[i]) === -1
, so that in case you have a string without a vowel, the loop still terminates when reaching string end.
function largestOfFour(arr) {
for(var i = 0;i < arr.length;i++){
for(var n = 0;n < arr[i].length ;n++){
var max =arr[0][0];
arr[i][n] > max ? (max = arr[i][n]) : max;
arr = max;
}
}
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
max
before your inner loop, and use arr[i][0]
. Store max
to some new variable/array after your inner loop.
@EpicTriffid What do you mean? The standard for looping an array uses its length property explicitly. You can even apply array functions to other array-likes, like
function removeVowels(str) {
return Array.prototype.filter.call(str, function(ch) { return "AIUEOaiueo".indexOf(ch) === -1; }).join("");
}
(I'd use return str.replace(/[aiueo]/gi, '');
instead, that's just an example)
"0"
and "1"
and a .length
property (array-like objects). If the object has property keys like "cat"
, then for loop doesn't help straight away.
const RECIPIES = {
spaghetti: {
ingredients: ["1 lb pasta", "2 jars Ragu"],
directions: [
"Add pasta to 4qts boiling water",
"stir occasionally and let boil for approx 10 mins",
"Remove from heat and drain water from pasta",
"Heat Ragu according to directions on jar"
]
},
pizza: {
ingredients: ["1 frozen Digorno Pizza"],
directions: ["Follow heating instructions on box", "Slice into 8 pieces"]
},
"tomato soup": {
ingredients: ["1 can Progresso Tomato Basil Soup"],
directions: [
"Use can opener to open can",
"Empty into a microwave safe bowl",
"Heat on high approximately 3 mins"
]
},
"wish sandwich": {
ingredients: ["2 slices of bread", "1 Wish"],
directions: ["While holding bread use wish to wish for meat", "Eat bread"]
},
"rubber biscuit": {
ingredients: ["1 rubber biscuit"],
directions: [
"Throw biscuit against wall",
"If biscuit doesn't bounce back into your mouth, you go hungry!"
]
}
};
Object.keys(RECIPIES).map((e,i) => console.log(e.toUpperCase()))
forEach
instead of map
if I weren't interested in the return values.
for...in
in insertion order.
Array.prototype.sort
being stable (not swapping the order of elements considered equal), even though that one is explicitly not guaranteed (yes, I did not say "not explicitly guaranteed"). It was considered a bug in Firefox.
var array = [];
function chunkArrayInGroups(arr, size) {
// Break it up.
for(var i =0;i<arr.length;i=i+size){
array.push(arr.slice(i,i+size));
}
console.log(array);
return array;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
:star2: 4394 | @masd925 |http://www.freecodecamp.com/masd925
array
doesn't reset between the calls.
prakashyadav008 sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4395 | @masd925 |http://www.freecodecamp.com/masd925
Hi all I have a question: if I run this
var regexWhitespace1 = /^[^\n ]*$/g;
var adV = "\n jeroen\n ";
var runAd = adV.match(regexWhitespace1);
console.log("test results in " + runAd);
it doesnt do anything except log null.. I want to match everything except for newlines and whitespace... I got this code from https://stackoverflow.com/questions/23235200/how-to-matches-anything-except-space-and-new-line
function chunkArrayInGroups(arr, size) {
var result = [];
while (arr.length>0) result.push(arr.splice(0,size));
return result;
}
for...in
loop is for iterating over object property keys (enumerable properties of the object and the prototype chain).
var array = [];
return str.slice(1) + str.slice(0,1)
return str.slice(2) + str.slice(0,2)
str = str.slice(2)
would change the string held in str
.
@EpicTriffid Better not use for..in on arrays or array-likes. First, there's no guaranteed order. Then, for..in walks through all enumerable properties, inherited or not. If I used a polyfill to add some method to Array.prototype
, and used a simple assignment instead of Object.defineProperty
, it would automatically be enumerable and would show up in the for..in over any array.
In a for loop using the length property, you control the order. You are never affected by enumerable non-numeric properties, because your index is numeric.
return str.slice(i) + str.slice(0, i) + "ay";
should work for any i
. So why do you say "it aint working"? What is the code you execute, what do you expect, what happens instead?
/\S+/g
?
bilaal-s sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8280 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
<script>
for (let i = 0; i < 10; i++) {
console.log(i);
setTimeout(function(){
console.log("the number is "+ i);
}, 1000)
}
</script>
When I ran this.. I am getting the output 0
1
2
3
4
5
6
7
8
9
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 5
the number is 6
the number is 7
the number is 8
the number is 9
var i=0
in the for loop , I am getting 0
1
2
3
4
5
6
7
8
9
the number is 10
var
, you create a global variable that all those callbacks use. So the number is 10
is printed 10 times.
i
ends up with value 10
and later those timeout events fire and callbacks are run.
settimeout
function to finish running. ?
setTimeout
just binds a function to the event. So it tells the browser to run the callback function after certain time has passed. That script runs almost immediately, and doesn't wait for callbacks to run.
i
s stored?
let
. So the variable stays alive on the closure of the callback. I am not too familiar with ES6, so eat my stew at arms length.
var
, all those callbacks would have access to the same variable on the global scope.
var
case , the i
value has reached 10. and it is available at global scope. So by the time setTimeout
is called it picks the last value of i
which is 10, Right? correct me if I am wrong
let
case each for loop
becomes a different block ?
var
, when any of those callback function is executed, i
is found on the global scope.
let
, it is found on the block scope created by a loop step.
function x() {
for (var i = 0; i < 10; i++) {
console.log(i);
setTimeout(function(){
console.log("the number is "+ i);
}, 1000)
}
}
venkateshwaran sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8281 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
i
, that's more space than one. But before that, you would have used a closure, which is probably even more overhead.
venkateshwaran sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4396 | @masd925 |http://www.freecodecamp.com/masd925
var
case I used closure, and that is more heavy?
let
, an implementation of the let
case would have used closure and caused more overhead.
var
appropriately would be better than using let
?
sjames1958gm sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4397 | @masd925 |http://www.freecodecamp.com/masd925
masd925 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8282 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
function generate(int) {
if (int === 1) {
// Make sure to join the characters as we create the permutation arrays
permutations.push(arr.join(''));
} else {
for (var i = 0; i != int; ++i) {
generate(int - 1);
swap(int % 2 ? 0 : i, int - 1); // why this cannot be altered using traditional if else ?
}
}
}
hi can anyone help explain the difference between this function and below function ?function generate(int) {
if (int === 1) {
// Make sure to join the characters as we create the permutation arrays
permutations.push(arr.join(''));
} else {
for (var i = 0; i != int; ++i) {
generate(int - 1);
if(int % 2 === 0){
swap (0,int-1);
}
else{
swap (int, int-1);
}
}
}
}
if ((i % 1 ) && (i % i)) {
prime.push(i)
}
this is what i have
function primes(start, end) {
var prime = []
for (var i = start; i <= end; i++) {
if ((i % 1 ) && (i % i)) {
prime.push(i);
}
}
return prime;
}
it returns empty array
int % 2 ? 0 : i
this does the if / else check of the second function.namethatisnottaken sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8283 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
kelechy sends brownie points to @catacid :sparkles: :thumbsup: :sparkles:
:cookie: 417 | @catacid |http://www.freecodecamp.com/catacid
@namethatisnottaken There is a difference: This is the first code changed to if / else
if (int % 2) {
swap(0, int-1); // so when int % 2 is not zero
} else {
swap(i, int-1); // here i is used not int
}
looks like the if / else are swapped and the else is using i not int
max
Hi all I have a question: why does this:
console.log (!undefined === "jack") ;
VM2539:1 false
undefined
console.log(!undefined === "jack");
VM2581:1 false
undefined
both return false?!
This is the right code:
console.log(!undefined === "jack");
//false
undefined
console.log(undefined === "jack");
// false
How can this be?
console.log(!undefined);
//true
console.log(undefined !== 'jack'); // should be true
zombiebirds sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 3573 | @moigithub |http://www.freecodecamp.com/moigithub
waingor sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4512 | @chrono79 |http://www.freecodecamp.com/chrono79
1==2
that will always be falsewaingor sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8284 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
//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 (i = 0; i < contacts[i].length; i++){
if (firstName && prop === true){
return firstName.prop;
} else (prop === false){
return "No such property";
} else (firstName === false){
return "No such contact";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
"No such contact"
outside of your loop
function trim(str, size) {
if (str.length > size){
return str.slice(0, (size - 3)) + '...';
}
if (str.length < 3) {
//this is the prob line
return str.slice(0, size) + '...'
}
else{
return str;
}
}
someone help me with an extra eye here, passes all except one test
```If the string is smaller than or equal to 3 characters then the length of the dots is not added to the string length.
e.g. trim("He", 1) should return "H..."```
str.length <= 3
addisonday sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles:
:star2: 2138 | @jluboff |http://www.freecodecamp.com/jluboff
document.querySelector("#destiny").style.display = 'none'
@Masd925 please help
`
function destroyer(arr) {
var here = arr.filter( function(val){
for (var i=1; i<arguments.length; i++)
{
if (val === arguments[i])
return false;
}
return true;
});
}
`
document.querySelector("#destiny").setAttribute("hidden", "");
roniquericketts sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1109 | @cmccormack |http://www.freecodecamp.com/cmccormack
arguments
will contain two arrays, your destroy as arguments[0]
and seek as arguments[1]
. your loop iterates over just those two items
arguments
inside the filter function are for that function not destroyer
return (val !== arguments[i])
//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 (i = 0; i < contacts[i].length; i++){
if (firstName && prop === true){
return contacts[firstName][prop];
} else if (prop === false){
return "No such property";
} else if (firstName === false){
return "No such contact";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
i < contacts.length
not contacts[i]`
firstName && prop === true
this is not valid syntax, you must make each comparison sperate ie. firstName === true && prop === true
But thats not going to work either, you want to actually check if contacts has those properties using something like .hasOwnProperty
const trim = (arr, size) => arr.length < 3 ? `${arr.slice(0, size)}...` : arr.length > size ? `${arr.slice(0, size-3)}...` : arr
addisonday sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles:
:star2: 2140 | @jluboff |http://www.freecodecamp.com/jluboff
date: “Wednesday”,
weather: “sunny”,
month: “August”
}
@junipberry And what format do you want the array to be?
[["date", "Wednesday"], ["weather"....]]
or
["date", "Wednesday", "weather"...]
or
["Wednesday", "sunny"...]
let obj = {
date: "Wednesday",
weather: "sunny",
month: "August"
};
let arr = [];
for(let key in obj) {
arr.push([key, obj[key]]);
}
console.log(arr); // Result: [ [ 'date', 'Wednesday' ], [ 'weather', 'sunny' ], [ 'month', 'August' ] ]
junipberry sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles:
:star2: 2141 | @jluboff |http://www.freecodecamp.com/jluboff
//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 (i = 0; i < contacts.length; i++){
if (contacts.hasOwnProperty([prop])){
return contacts.firstName[prop];
} else if (prop === false){
return "No such property";
}
}
if (firstName === false){
return "No such contact";
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
contact.hasOwnProperty(prop)
prop
correct?
prop
is our parameter which acts as a variable, so it's assigned by the function call (in this case, it defined as "likes"
). By adding brackets, you're telling it look for ["likes"]
instead of "likes"
arr
i < contacts.length
, which is what we want. @sjames1958gm is refering to actually inside the for loop
@JLuboff
could you take a look at this:
```function getKeys(obj){
let myArr = [];
for(let key in obj){
myArr.push([key,obj[key]]);
}
return myArr;
}
```
function getKeys(obj){
let myArr = [];
for(let key in obj){
myArr.push([key,obj[key]]);
}
return myArr;
}
Write a function called "getKeys" which returns an array of all the input object's keys.
Example input:
{
name : 'Sam',
age : 25,
hasPets : true
}
Function's return value (output) :
['name', 'age', 'hasPets’]
Do not use "Object.keys" to solve this prompt.
Note that your function should be able to handle any object passed in it.
E.g. it should also handle an input like:
{
a : 'a',
number : 11,
hungry : true,
grammyWins : 1
}
Function's return value (output):
['a', 'number', 'hungry', 'grammyWins’]
myArr.push(key);
junipberry sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles:
:warning: junipberry already gave jluboff points
const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');
let lastChecked;
function handleCheck(e) {
lastChecked = this;
}
checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));
detailUrl = "https://wind-bow.glitch.me/twitch-api/channels/" + user;
$("#streamers").append("<div class='user' id="+user+"></div>");
$.getJSON(detailUrl,function(detail){
streamUrl = "https://wind-bow.glitch.me/twitch-api/streams/" + user;
$.getJSON(streamUrl, function(current){
streamUrl
user by the time the second JSON call occurs
return "No such contact"
outside your loop, you loop is already assessing (inside or at least it should be ;)) that the user exists or doesn't
@JLuboff Here is what I have now.
//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 (i = 0; i < contacts.length; i++){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
} else {
return "No such property";
}
}
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
Two of the 5 tests pass
F "Kristian", "lastName" should return "Vos"
F "Sherlock", "likes" should return ["Intriguing Cases", "Violin"]
P "Harry","likes" should return an array
F "Bob", "number" should return "No such contact"
P "Akira", "address" should return "No such property"
for (var i = 0; i < 5; i++) {
return i; // how many times will this line of code execute?
}
html: '<p style="color:green;"><b>Dear Sir.</b>I this is a message from your automatic mailingservice</p><div style = "position: relative; background-image: url('http:\\/\\/willpenman.com/teaching/armin0_img.png'); background-repeat: no-repeat; background-position: center top; background-size: cover; min-height: 310px;"> </div>'
var mail = { html: '<p style="color:green;"><b>Dear Sir.</b>I this is a message from your automatic mailingservice</p><div style = "position: relative; background-image: url('http:\\/\\/willpenman.com/teaching/armin0_img.png'); background-repeat: no-repeat; background-position: center top; background-size: cover; min-height: 310px;"> </div>'
};
contacts[i].firstName
matches the firstName
from the parameter.
http:\\/\\/
???
addisonday sends brownie points to @kumquatfelafel and @roxroy :sparkles: :thumbsup: :sparkles:
:cookie: 586 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
:star2: 1096 | @roxroy |http://www.freecodecamp.com/roxroy
@addisonday Check property if and only if first names are the same. Otherwise, do not check for property. No such property
basically means "contact with this name exists, but said contact doesn't have the given property". So if the first name I'm looking for is Larry, but the contact I'm looking at is Sal... if Sal doesn't have the given property, then this in and of itself is not justification for returning no such property
. I should only be returning no such property if there is a contact with the first name of Larry, who doesn't have said property.
Remember, return statement, if executed, will halt the loop and the function immediately returning the specified value. Currently, your "No such contact" (which should occur when none of the contacts has the given first name) return statement is never executed because one of your other two return statements is executed no matter what in the first iteration of your for loop. (this statement based upon code above, but may not be true for whatever you have now)
//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 (i = 0; i < contacts.length; i++){
if (contacts[i].firstName === firstName){
if (contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
thayyebsalim sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles:
:star2: 2142 | @jluboff |http://www.freecodecamp.com/jluboff
function toaster(b){
return (b == 'white bread') ? '1 min' : (b == 'frozen white bread') ? '1.5 mins' :
(b == 'brown bread') ? '2 mins' : (b == 'frozen brown bread') ? '3 mins' :
"Please do not put that in the toaster!";
}
Expected: '1 min', instead got: 'Please do not put that in the toaster!'
@addisonday that's good. :)
I think nested if statements like you have is best option here. Without it your for loop would probably look something like...
for(blahblah) {
if (contacts[i].firstName !== firstName)
continue;
else if(contacts[i].hasOwnProperty(prop)
return contacts[i][prop];
else
return "No such property";
}
this... which, coding-wise, is kinda weird
kelechy sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 587 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
document.querySelectorAll("div > .grids");
tiagocorreiaalmeida sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4513 | @chrono79 |http://www.freecodecamp.com/chrono79
class Player extends Gfx{
constructor(){
if(SERVER === false){ //to make sure the server doesn't run the super constructor because it contains things that are just not needed in the server
super();
}
}
}
roniquericketts sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1114 | @cmccormack |http://www.freecodecamp.com/cmccormack
grids.forEach(grid=>grid.addEventListener...
roniquericketts sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:warning: roniquericketts already gave cmccormack points
lufter sends brownie points to @roxroy :sparkles: :thumbsup: :sparkles:
:star2: 1097 | @roxroy |http://www.freecodecamp.com/roxroy
Hi all, I have a question. I have a crawler that I will let run on my mac terminal. It's written in NodeJS. I will have it scan 1 specific page every 5 seconds. Because I want I will do it using:
setInterval(function(){ alert("Hello"); }, 3000);
I want it to keep running the entire day but I just have 1 question: once it's running, how will I make it stop!! lol
function destroyer(arr) {
var args = Array.from(arguments);
var here = arr.filter( function(val) {
for (var i=1; i<args.length; i++)
return (val !== args[i]);
});
return here;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
Pft... everybody knows it's the blue wire. I'll prove it!
:boom:
@cmccormack This worked
function destroyer(arr) {
var args = Array.from(arguments);
var here = arr.filter( function(val) {
return !args.includes(val);
});
return here;
}
But i'm still breaking my head with the previous code
@tiagocorreiaalmeida
And make it like this instead, to hide overlay area and pop-up.
Because right now you only hide half of popup
$('.col-1 a').click(function(){
console.log("hi");
multiplayer = false;
$("#popup1").fadeOut();
});
$('.col-2 a').click(function(){
console.log("hi2");
multiplayer = true;
$("#popup1").fadeOut();
});
$('.content h3').text("Choose your Mark").fadeIn();
//shared js code between server and client
class Player extends Gfx{
constructor(){
if(SERVER === false){ //this is the line that says SERVER is not defined when it is defined in app.js
super();
}
}
}
if(module.exports){
module.exports = {player};
}
//app.js on node
const SERVER = true;
let PlayerClass = require("player.js").player;
let testPlayer = new PlayerClass();
// giving error that SERVER is not defined
$('div span').text('Hello World');
.text()
returns, if it's an element then should work
@tiagocorreiaalmeida
You may use has to get the required result
$(".content:has(h3)").text("Hello World");
Basically 'All elements with class ".content" that have a <h3> element' will display text "Hello World"
hi guys. i think i found a but. im on the algo search and replace. and this is my code
function myReplace(str, before, after) {
var myRegex = RegExp('(\\w*'+before+'\\w*)','gi');
return str.replace(myRegex,after);
}
myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
its returning right but i have an error. like what???
this.uid = obj.uid || "none";
^
ReferenceError: this is not defined
@artoodeeto
var re = new RegExp("\\w+");
var re = /\w+/;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
function handleProgress() {
const percent = video.currentTime / video.duration * 100;
progressBar.style.flexBasis = `${percent}%`;
}
percent + '%'
?
flex-basis: 50
wouldn't work, but flex-basis: 50%
would
percent + '%'
equivalent to ${percent}%
? That's what seems weird
abohannon sends brownie points to @kumquatfelafel and @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4514 | @chrono79 |http://www.freecodecamp.com/chrono79
:cookie: 588 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
$('.choicex').click(function(){
console.log("Here");
if(multiplayer){
userMark = 'X';
secondPlayer = "O";
}else{
userMark = 'X';
computerMark = "O";
}
$("#popup1").fadeOut();
});
abidrahim sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1115 | @cmccormack |http://www.freecodecamp.com/cmccormack
sandsbe sends brownie points to @jluboff and @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 2143 | @jluboff |http://www.freecodecamp.com/jluboff
:star2: 4515 | @chrono79 |http://www.freecodecamp.com/chrono79
var gooloc ="https://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat + "," + long +"&key=AIzaSyBUzuWvyNu66-dU5DW8DfMqNQ87JgFPCUs";
var province;
var state;
var city;
$.getJSON(gooloc, function(loc){
$("#locate").html(loc.results.long_name.country);
city=loc.address_components.administrative_area_level_1;
state=loc.adress_components.country;
province=loc.address_components.administrative_area_level_2;
}); // closing getjson gooloc
$("#locate").html(loc);
for (let i=0; i<myLgth; i++){
myObj[array[i,[0]]]= array[i,[1]];
}
loc
to console in your getJSON to see if it's getting a response? Did you check your browser console for errors?
myObj[array[i,[0]]]= array[i,[1]];
? An assignment statment in your object lookup
function listToObject(array) {
let myObj = {};
let myLgth = array.length;
for (let i=0; i<myLgth; i++){
myObj[array[i,[0]]]= array[i,[1]];
}
return myObj;
}
bc I want to turn an array of arrays into key-value pairs
array[i,[0]]
array
might look like?
> var arr = [[1,2,3], [4,5, [6,7]]]
> arr[1][2] // arr[1] grabs the second item in the array, then the following [2] grabs the third item from THAT array
[ 6, 7 ]
[
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
]
myObj[array[i][0]] = array[i][1]]
junipberry sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1116 | @cmccormack |http://www.freecodecamp.com/cmccormack
so then, just want to be sure, this part of the function:
for (let i=0; i<myLgth; i++){
myObj[array[i][0]]= array[[i][1]];
is effectively looping the assignment of index [0] and index [1] to object key-value, respectively.
myLgth.length
@junipberry?
let myLgth = array.length;
was defined in her code up above a bit
@jimtryon , its from this:
function listToObject(array) {
let myObj = {};
let myLgth = array.length;
for (let i=0; i<myLgth; i++){
myObj[array[i][0]]= array[[i][1]];
}
return myObj;
}
so it should be fine.
.length
property
jimtryon sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1117 | @cmccormack |http://www.freecodecamp.com/cmccormack
=array[i][1]
console.log('freecode'.split('').splice(0,1,"fast"));
junipberry sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:warning: junipberry already gave cmccormack points
@cmccormack
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]
this is the sample
var name = function () {
fs.readdir(dir, (err, files) => {
return files.length + 1;
});
}
fs.readFile
dir
?
dir
is a valid path?
console.log(files)
?
dir
is undefined
// Use the mv() method to place the file somewhere on your server
var dir = './uploads';
fs.readdir(dir, (err, files) => {
return files.length + 1;
});
sampleFile.mv('./uploads/' + name + '.jpg', function(err, res) {
if (err) {
return res.status(500).send(err);
}
res.redirect('/dashboard');
});
console.log(files.length)
in your function
+1
?
files.length + 1
sampleFile.mv('./uploads/' + RANDOMVALUE + '.jpg',