Get help on our basic JavaScript and Algorithms Challenges. If you are posting code that is large use Gist - https://gist.github.com/ paste the link here.
function multiplyAll(arr) {
return arr.reduce(function(a, b) {return a.concat(b)}).reduce(function(a, b) {return a * b});
}
arr =
is not needed, does not change anything.
@dagman Loops are quicker, each function call has some overhead (so for long code blocks the overhead is relatively smaller). I think I would add some standard values, so that it works on empty array, like
return arr.reduce((arr1, arr2)=>arr1.concat(arr2), []).reduce((prod, num) => prod*num, 1);
, or use
return [].concat.apply([], arr).reduce((prod, num) => prod*num, 1);
// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
myObj.hasOwnProperty("checkProp");
return myObj[checkProp];
}
// Test your code by modifying these values
checkObj("house");
how to return "not found" if my object hasn't has the property of hasOwnProperty function
http://
in front of the api.openweathermap.org
, that one was missing on the codepen...
lizzieshipton sends brownie points to @coymeetsworld and @blauelf :sparkles: :thumbsup: :sparkles:
:star: 561 | @coymeetsworld | http://www.freecodecamp.com/coymeetsworld
:star: 1641 | @blauelf | http://www.freecodecamp.com/blauelf
//
for same-protocol-as-here), your URL is relative path on the same server. Like all those dead links with href="www.google.com"
. Simply does not work, as this could also be a path on your server (relative to current path), and the browser should not guess.
if object has this property
return the property
else
return a message saying not found
//
is not of much help for many free APIs, as they only exist on HTTP.
function checkObj(checkProp) {
// Your Code Here
if (myObj.checkProp ===true){
myObj.hasOwnProperty("checkProp");
return myObj[checkProp];
}
else {
return "not Found";
}
} @sludge256
if (myObj.hasOwnProperty(checkProp))
- you want to know whether myObj
has a property of the name stored in argument checkProp
myObj.checkProp
is same as myObj["checkProp"]
, and not what you want. You did it right in the return statement, and that's the only place where you need it anyway.
hasOwnProperty()
inside your conditional it will evaluate to a boolean.
limelightbuzz sends brownie points to @leftynaut :sparkles: :thumbsup: :sparkles:
:star: 483 | @leftynaut | http://www.freecodecamp.com/leftynaut
'''
var max;
var perc;
var calculatedResult;
var enterWeight;
var enterPercentage;
var plates = [45, 35, 25, 15, 10, 5, 2.5];
function calculateWeight () {
max = document.getElementById('max');
perc = document.getElementById('percentage');
enterWeight = max.value;
enterPercentage = perc.value;
calculatedResult = enterWeight * enterPercentage / 100;
if (document.getElementById('male').checked === true) {
calculatedResult = calculatedResult - 45;
} else {
calculatedResult = calculatedResult - 35;
}
console.log('enterWeight', enterWeight);
console.log('enterPercentage', enterPercentage);
console.log(calculatedResult);
document.getElementById('result').innerHTML = 'Load Up ' + calculatedResult + ' lbs'
}
var plates = [45, 35, 25, 10, 5, 2.5];
var putThemOn = [0,0,0,0,0,0];
function whatPlates(calculatedResult){
var i = 0;
while (i < plates.length) {
if (2plates[i]<=calculatedResult) {
calculatedResult = calculatedResult - (2plates[i]);
putThemOn[i] += 2;
}
if (2*plates[i]>=calculatedResult) {
i++;
}
}
return putThemOn;
}
console.log(whatPlates(500));
:bulb: to format code use backticks! ``` more info
'''
var max;
var perc;
var calculatedResult;
var enterWeight;
var enterPercentage;
var plates = [45, 35, 25, 15, 10, 5, 2.5];
function calculateWeight () {
max = document.getElementById('max');
perc = document.getElementById('percentage');
enterWeight = max.value;
enterPercentage = perc.value;
calculatedResult = enterWeight * enterPercentage / 100;
if (document.getElementById('male').checked === true) {
calculatedResult = calculatedResult - 45;
} else {
calculatedResult = calculatedResult - 35;
}
console.log('enterWeight', enterWeight);
console.log('enterPercentage', enterPercentage);
console.log(calculatedResult);
document.getElementById('result').innerHTML = 'Load Up ' + calculatedResult + ' lbs'
}
var plates = [45, 35, 25, 10, 5, 2.5];
var putThemOn = [0,0,0,0,0,0];
function whatPlates(calculatedResult){
var i = 0;
while (i < plates.length) {
if (2plates[i]<=calculatedResult) {
calculatedResult = calculatedResult - (2plates[i]);
putThemOn[i] += 2;
}
if (2*plates[i]>=calculatedResult) {
i++;
}
}
return putThemOn;
}
console.log(whatPlates(500));
:bulb: to format code use backticks! ``` more info
zico0o sends brownie points to @blauelf and @sludge256 :sparkles: :thumbsup: :sparkles:
:star: 1642 | @blauelf | http://www.freecodecamp.com/blauelf
:star: 2224 | @sludge256 | http://www.freecodecamp.com/sludge256
zico0o sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:warning: zico0o already gave blauelf points
0, null, false, undefined, NaN, ""
. They have in common that truthy values when converted or coerced to boolean become true
, and falsy values become false
. Most functions that expect a boolean in reality also accept truthy/falsy values. That's how while (arr.length && !func(arr[0])) arr.shift();
works, A&&B evaluates to A if A is falsy, else to B.
collection
to see if pre
is truthy or falsy on all elements of the array, do I need a giant OR statement such as if collection[i] === 0 || null || ... etc.
?
var max;
var perc;
var calculatedResult;
var enterWeight;
var enterPercentage;
var plates = [45, 35, 25, 15, 10, 5, 2.5];
function calculateWeight () {
max = document.getElementById('max');
perc = document.getElementById('percentage');
enterWeight = max.value;
enterPercentage = perc.value;
calculatedResult = enterWeight * enterPercentage / 100;
if (document.getElementById('male').checked === true) {
calculatedResult = calculatedResult - 45;
} else {
calculatedResult = calculatedResult - 35;
}
console.log('enterWeight', enterWeight);
console.log('enterPercentage', enterPercentage);
console.log(calculatedResult);
document.getElementById('result').innerHTML = 'Load Up ' + calculatedResult + ' lbs'
}
var plates = [45, 35, 25, 10, 5, 2.5];
var putThemOn = [0,0,0,0,0,0];
function whatPlates(calculatedResult){
var i = 0;
while (i < plates.length) {
if (2*plates[i]<=calculatedResult) {
calculatedResult = calculatedResult - (2*plates[i]);
putThemOn[i] += 2;
}
if (2*plates[i]>=calculatedResult) {
i++;
}
}
return putThemOn;
}
console.log(whatPlates(500));
function doubleIt(inpoot) {
var fortyFive = inpoot[0];
var thirtyFive = inpoot[1];
var twentyFive = inpoot[2];
var ten = inpoot[3];
var five = inpoot[4];
var twoPointFive = inpoot[5];
return"Put on " + fortyFive + " 45 lb. plates, " + (fortyFive/2) + " on each side," +
"\n Put on " + thirtyFive + " 35 lb. plates, " + (thirtyFive/2) + " on each side," +
"\n Put on " + twentyFive + " 25 lb. plates, " + (twentyFive/2) + " on each side," +
"\n Put on " + ten + " 10 lb. plates, " + (ten/2) + " on each side," +
"\n Put on " + five + " 5 lb. plates, " + (five/2) + " on each side," +
"\n Put on " + twoPointFive + " 2.5 lb. plates, " + (twoPointFive/2) + " on each side";
}
console.log(doubleIt(putThemOn));
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp)){
return myObj[checkProp];
}
else
return "Not Found";
}
// Test your code by modifying these values
checkObj("house");
here house is passed at checkObj Arg (checkProp) and also to hasOwnProperty (checkProp) to be checked . but can't check check
@kmulligan You could
if (collection[i] === 0 || collection[i] === null || collection[i] === false || collection[i] === undefined || collection[i] === "" || collection[i] !== collection[i]) {
console.log("Falsy!")
}
or you could simply
if (!collection[i]) {
console.log("Falsy");
}
if(!collection[i])
into a function to use array.every(callback)
?
function(elem) { return pre in elem && elem[pre]; }
(if pre is not a key to elem, elem[pre] would silently fail and evaluate to undefined
, which is also falsy, so one could skip the first part and just return elem[pre]
)
function truthCheck(collection, pre) {
// Is everyone being true?
function hasPre(collection,pre) {
return collection[pre];
}
return collection.every(hasPre);
}
truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
function lookUpProfile(firstName, prop){
// Only change code below this line
var contact = "";
for(var i = 0; i < contacts.length; i++){
if(contacts[i]["firstName"] == firstName){
if(contacts[i][prop]){
return contacts[i][prop];
}else{
return "No such property";
}
}else{
return "No such contact";
}
}
// Only change code above this line
}
function lookUpProfile(firstName, prop){
// Only change code below this line
var contact = "";
for(var i = 0; i < contacts.length; i++){
if(contacts[i]["firstName"] == firstName){
if(contacts[i][prop]){
return contacts[i][prop];
}else{
return "No such property";
}
}else{
return "No such contact";
}
}
// Only change code above this line
}
function truthCheck(collection, pre) {
function truthyPre(elem) {
return elem[pre];
}
return collection.every(truthyPre);
}
```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 lookUpProfile(firstName, prop){
// Only change code below this line
var contact = "";
for(var i = 0; i < contacts.length; i++){
if(contacts[i]["firstName"] == firstName){
if(contacts[i][prop]){
return contacts[i][prop];
}else{
return "No such property";
}
}else{
return "No such contact";
}
}
// Only change code above this line
}
truthyPre
can ... use? if that's the right term, use pre
even though it wasn't part of the (elem)
part?
contacts[i].hasOwnProperty(prop)
or prop in contacts[i]
to test for property, as a falsy value would trigger the "No such property" path.
tylergross sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star: 1643 | @blauelf | http://www.freecodecamp.com/blauelf
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i=0;i<contacts.length;i++) {
console.log(contacts[i].firstName);
if ( firstName === contacts[i].firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
else if ( firstName !== contacts[i][firstName]) {
return "No such contact";
}
else if (!contacts[i].hasOwnProperty(prop)) {
return "No such property";
}
}
// Only change code above this line
}
elem
since you are testing the elements in collection
not the collections in collection
?
kmulligan sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star: 1644 | @blauelf | http://www.freecodecamp.com/blauelf
Hey guys, little theory question for anyone with a bit of JS experience: which of these methods for iterating through an array is considered better?
//https://www.freecodecamp.com/challenges/iterate-through-an-array-with-a-for-loop
function incrementArrayOutput(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
// is this 'better'?
function traverseArrayOutput(arr) {
for (var index in arr) {
console.log(arr[index]);
}
}
var arr = [1,2,3];
incrementArrayOutput(arr);
traverseArrayOutput(arr);
I ask because to me the one I called 'traverse' seems cleaner, but the FCC lesson teaches the 'increment' method. I was wondering if that was because it was better practice, or just because the increment method works when only accessing odd/even arr elements and they didn;t want to teach both mehods? Any ideas?
i need help with this exercise:
One way to think of a multi-dimensional array, is as an array of arrays. When you use brackets to access your array, the first set of bracket refers to the entries in the outer-most array, and each subsequent level of brackets refers to the next level of entries inside.
Example
var arr = [
[1,2,3],
[4,5,6],
[7,8,9],
[[10,11,12], 13, 14]
];
arr[0]; // equals [1,2,3]
arr1; // equals 6
arr[3]0; // equals 11
Instructions
Read from myArray using bracket notation so that myData is equal to 8
jacksonbates sends brownie points to @jsodin :sparkles: :thumbsup: :sparkles:
:star: 228 | @jsodin | http://www.freecodecamp.com/jsodin
@aGirlWhoCodes ~~~js
var str = "dog gone good";
console.log(str.replace(/\s/g,''))
~~~
returned "doggonegood" as expected
var str = "dog gone good";
console.log(str.replace(/\s/g,''))
returned "doggonegood" as expected"
@henrywashere
var arr = [
[1,2,3],
[4,5,6],
[7,8,9]]
console.log(arr[0]); // [1, 2, 3]
console.log(arr[0][1]); // 1
Does this help?
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
myObj.hasOwnProperty(checkProp);
return "Not Found";
}
var array = [1, 2, 3]
But instea of numbers it can have another array put inside of it.
js
<// Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
myObj.hasOwnProperty("checkProp");
if (true) {
return myObj[checkProp];
}
else {
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("house");
>
var array_num = [1, 2, 3]
console.log(array_num[0]); // 1
// Notice we have two sets of brackets here [[]]
var array_array = [[1,2,3]]
console.log(array_array[0]); // [1,2,3]
@cenamorado1
function palindrome(str) {
str = str.toLowerCase();
str = str.replace(/\s/g, "");
var spaces = str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]//,'');
var arr = spaces.split("");
var reversing = arr.reverse();
var end = reversing.join("");
if (str == end) {
return true;
} else {
return false;
}
}
if (myObj.hasOwnProperty("checkProp");) {
return myObj[checkProp];
}
else {
return "Not Found";
}
ndburrus sends brownie points to @isymm :sparkles: :thumbsup: :sparkles:
:star: 309 | @isymm | http://www.freecodecamp.com/isymm
$(elem).on("click", function() {})
```$(elem).click()...
@ndburrus Sorry for got to remove the quote marks and the semi colon.
if (myObj.hasOwnProperty(checkProp)) {
return myObj[checkProp];
}
else {
return "Not Found";
}
Just remember whatever you put inside the brackets of an if statement will be evaluated.
$(elem).on("click", function() {})
$(elem).click()...
chrisl108 sends brownie points to @isymm :sparkles: :thumbsup: :sparkles:
:star: 310 | @isymm | http://www.freecodecamp.com/isymm
if (true) {
// THIS WILL ALWAYS HAPPEN YOU CAN'T PUT TRUE AS YOUR CONDITION
} else {
// THIS CODE WILL NEVER EXECUTE BECASUE YOUR STATEMENT IS ALWAYS TRUE!
}
if(this statement is true) {
//do this
} else {
// do this.
}
myObj.hasOwnProperty(myProp)
return true or false...
On the Testing Object for Properties lesson, I figured out the answer. // Setup
var myObj = {
gift: "pony",
pet: "kitten",
bed: "sleigh"
};
function checkObj(checkProp) {
// Your Code Here
if (myObj.hasOwnProperty(checkProp) === true) {
return myObj[checkProp];
} else {
return "Not Found";
}
}
// Test your code by modifying these values
checkObj("pet");
var obj = {
foo : 1,
bar : 2,
checkProp: 'woops'
}
function check(checkProp) {
console.log(obj[checkProp]);
console.log(obj.checkProp);
}
check(foo); // 1 "woops"
@kevinpschwert
var checkProp = puppies;
obj[checkProp] //Will look for puppies
obj.checkProp // Will look for a property called checkProp
if
s?
@96street A quick solution would be to add the first three slides to the end then once it reaches the end -2 postion reset to slide 1.
like this.
96street sends brownie points to @isymm :sparkles: :thumbsup: :sparkles:
:star: 311 | @isymm | http://www.freecodecamp.com/isymm
my assignment looks like this Compound Assignment With Augmented Addition
In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:
myVar = myVar + 5;
to add 5 to myVar. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
One such operator is the += operator.
myVar += 5; will add 5 to myVar.
Instructions
Convert the assignments for a, b, and c to use the += operator.
var a = 3;
var b = 17;
var c = 12;
// Only modify code below this line
a = a + 12;
b = 9 + b;
c = c + 7;
var number = 5;
//Long form would be
number = number + 5;
//short form
number += 5;
var number = 5
// new number = old number (5) + 5
number = number + 5;
I keep getting
TypeError: Cannot assign to read only property '0' of string 'Hellow World'
My code is
// Setup
var myStr = "Jello World";
// Only change code below this line
myStr = "Hello World";
myStr[0] = "H"; // Fix Me
am3ricanpaladin sends brownie points to @lsymm :sparkles: :thumbsup: :sparkles:
:warning: could not find receiver for lsymm
var number = 6;
number = 3;
console.log(number) ; // 3
number = number +5;
// is the same as saying make number now equal to 3 + 5.
myStr = "Hello World"
myStr[0] = "H";
// Setup
var myStr = "Jello World";
// Only change code below this line
myStr[0] = "H"; // Fix Me
myStr[0] = "H";
with myStr = "Hello World";
reapnsow sends brownie points to @r0djm4n and @isymm :sparkles: :thumbsup: :sparkles:
:star: 225 | @r0djm4n | http://www.freecodecamp.com/r0djm4n
:star: 312 | @isymm | http://www.freecodecamp.com/isymm
// Setup
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
if (value!=="") {
if (prop!=="tracks") {[id][prop]=value;}
else {tracks.push(value);} }
else {delete [prop];}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CS",
"8T",
"LP" ],
"gold": true
}
// Add record here
];
does that mean that I have to add the code before the ]; or after ?
need help with this:
An easy way to append data to the end of an array is via the push() function.
.push() takes one or more parameter and "pushes" it onto the end of the array.
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]
Instructions
Push ["dog", 3] onto the end of the myArray variable.
i wrote ::
arr.push("dog", 3);
jw1540 sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star: 946 | @khaduch | http://www.freecodecamp.com/khaduch
henrywashere sends brownie points to @jw1540 :sparkles: :thumbsup: :sparkles:
:star: 150 | @jw1540 | http://www.freecodecamp.com/jw1540
// Setup
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
if (value!=="") {
if (prop!=="tracks") {collection[id][prop]=value;}
else {collection[id][prop].push([value]);} }
else {delete [prop];}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
ITS NOT WORKING...i wrote
var myArray = arr.push("dog", 3);
function nextInLine(arr, item) {
// Your code here
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
arr.push(‘dog’, 3)
returns the length of the array
var myArray = []
myArray.push(‘dog’, 3)
var myArray = [‘dog’, 3]
// Setup
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: [
"Let It Rock",
"You Give Love a Bad Name"
]
},
2468: {
album: "1999",
artist: "Prince",
tracks: [
"1999",
"Little Red Corvette"
]
},
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
if (value!=="") {
if (prop!=="tracks") {collection[id][prop]=value;}
else {collection[id][prop].push(value);} }
else {delete [prop];}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
var myArray = [];
myArray.push(["dog", 3]);
@ALMY91 here is it:
change this: collection[id][prop].push(value)
to
collection[id].tracks.push(value);
@henrywashere I just looked at when I did the challenge, I have this:
```
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line.
myArray.push(["dog", 3]);
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line.
myArray.push(["dog", 3]);
:warning: henrywashere already gave jw1540 points
henrywashere sends brownie points to @jw1540 :sparkles: :thumbsup: :sparkles:
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
// Only change code below this line
var gloveBoxContents = "myStorage.car.inside[glove box]"; // Change this line
almy91 sends brownie points to @pmohdameen :sparkles: :thumbsup: :sparkles:
:star: 265 | @pmohdameen | http://www.freecodecamp.com/pmohdameen
Hey guys so I'm trying to add to this json object. the instructions are to make a new album and have artist title release year and format properties but the tests are saying it doesn't have any properties, any ideas?
// example code
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CS",
"8T",
"LP" ],
"gold": true
}
];
// Add record here
myMusic[1] = [
{
"artist": "Childish Gambino",
"title": "Retro [rough]",
"release_year": 2015,
"formats": [
"CD",
"8T" ],
}
];
// example code
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CS",
"8T",
"LP" ],
"gold": true
}
];
// Add record here
myMusic[1] = [
{
"artist": "Childish Gambino",
"title": "Retro [rough]",
"release_year": 2015,
"formats": [
"CD",
"8T" ],
}
];
var audio = new Audio('http://picosong.com/static/widget/index.html?file=/cdn/789b3fc71aa1e16d256e861ef0965fb1.mp3&autoplay=true');
audio.play();
@ZctrapCoding
var audio = {};
audio['x'] = new Audio();
audio['x'].src = url;
audio['x'].play()
I think that should work..
function bouncer(arr) {
var fix = [];
function isTrue(value) {
return value !== false;
}
var newArr = arr.filter(isTrue);
return newArr;
}
bouncer([7, NaN, null, 2, undefined]);
returns [7, null, null, 2, null]
return
line like value !== null && value !== "";
it still returns null
in place of NaN
. Anyone know why?
Hey, in order to convert Celsius to Farenheit, I have the following solution that doesn't work:
Can someone please explain what I'm doing wrong and how to fix it:
function convertToF(celsius) {
// Only change code below this line
var convertToF = 9/5 + 32;
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
convertToF(20);
convertToF(10);
convertToF(0);
convertToF(-10);
convertToF(-20);
celsius
and returns fahrenheit
, but what you've added doesn't use either of those.
celsius
and doesn't return that value as fahrenheit.
function convertToF(celsius) {
// Only change code below this line
var fahrenheit = (9/5 + 32);
// Only change code above this line
return fahrenheit;
}
// Change the inputs below to test your code
convertToF(30);
while(change>=0.01 && pennies>0)
{
console.log(change);
ansPennies+=0.01;
console.log(typeof ansPennies);
console.log(ansPennies = " old PENNIES");
ansPennies = ansPennies.toFixed(2);
pennies-=0.01;
change-=0.01;
}
hi, I would need some help with Stemroller problem. When I enter the tests manually into the code they give the correct output however they don't pass.
var my_arr = [];
var steamrollArray = function (arr) {
if(typeof(arr) == "object") {
for(var i = 0; i < arr.length; i++) {
steamrollArray(arr[i]);
}
}
else {
my_arr.push(arr);
}
return my_arr;
};
steamrollArray([1, {}, [3, [[4]]]]);
Any ideas?
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i =0 ; i< arr.length;i++) {
for(var j=0 ; j<arr[i].length; j++)
console.log(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]]);
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i =0 ; i< arr.length;i++) {
for(var j=0 ; j<arr[i].length; j++)
console.log(arr[i][j]);
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]]);
parse
it before calling the the toFixed()
method. This method converts a number into a string, so I think the second time around your while loops fails because ansPennies
is now a string?
var Bike = function(currentGear) {
// Only change code below this line.
var gear = currentGear;
this.getGear = function() {
return gear;
}
this.setGear = function() {
return gear;
}
};
almy91 sends brownie points to @kirbyedy :sparkles: :thumbsup: :sparkles:
:star: 862 | @kirbyedy | http://www.freecodecamp.com/kirbyedy
radascript sends brownie points to @jlipschitz :sparkles: :thumbsup: :sparkles:
:star: 115 | @jlipschitz | http://www.freecodecamp.com/jlipschitz
this.setGear = function(val) {
gear=val;
}
ydeepk sends brownie points to @paulmanning :sparkles: :thumbsup: :sparkles:
:star: 286 | @paulmanning | http://www.freecodecamp.com/paulmanning
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i =0 ; i< arr.length;i++) {
for(var j=0 ; j<arr[i].length; j++)
console.log (arr[i][j]);
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]]);
while(change>=0.01 && pennies>0)
{
console.log(change);
ansPennies+=0.01;
console.log(typeof ansPennies);
console.log(ansPennies = " old PENNIES");
ansPennies = parseFloat(ansPennies.toFixed(2));
pennies-=0.01;
change-=0.01;
}
```js
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i =0 ; i< arr.length;i++) {
for(var j=0 ; j<arr[i].length; j++)
console.log (arr[i][j]);
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]]);
```
parseFloat(ansPennies).toFixed(2)
and it runs but typeof returns string each time. it does increment and decrease though
product*=arr[i][j];
console.log(product);
@Radascript
while(change>=0.01 && pennies>0)
{
console.log(change);
parseFloat(ansPennies+=0.01);
console.log(typeof ansPennies);
console.log(ansPennies + " old PENNIES");
ansPennies = parseFloat(ansPennies.toFixed(2));
console.log(ansPennies + " new PENNIES");
pennies-=0.01;
change-=0.01;
}
Give this a shot
radascript sends brownie points to @jlipschitz :sparkles: :thumbsup: :sparkles:
:warning: radascript already gave jlipschitz points
ansPennies+=0.01
at the top was throwing it off for some reason but worked when i forced it to be a float. also you had console.log(ansPennies = " old Pennies)
which i switched out to +
zerazera sends brownie points to @chrisl108 :sparkles: :thumbsup: :sparkles:
:star: 79 | @chrisl108 | http://www.freecodecamp.com/chrisl108
almy91 sends brownie points to @zerazera :sparkles: :thumbsup: :sparkles:
:star: 368 | @zerazera | http://www.freecodecamp.com/zerazera
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i =0 ; i< arr.length;i++) {
for(var j=0 ; j<arr[i].length; j++)
console.log(arr[i][j]);
product*=arr[i][j];
}
// Only change code above this line
console.log(product);
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
console.log(string2);
but it is not working, help me please. here is my code function palindrome(str) {
// Good luck!
var expression = /\W\s/g;
var string1 = str.replace(expression);
var string2 = string1.toLowerCase();
console.log(string2);
var string3 = function reverse(string2){
return string2.split("").reverse().join("");
};
if(string3 === str){
return true;
}
else {
return false;
}
}
palindrome("eye");
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i =0 ; i< arr.length;i++) {
for(var j=0 ; j<arr[i].length; j++)
{
console.log(arr[i][j]);
product*=arr[i][j];
}
}
// Only change code above this line
console.log(product);
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
function whereAreYou(collection, source) {
// What's in a name?
var arr = [];
var sourceProperties = Object.keys(source);
// Only change code below this line
for(var a = 0;a < collection.length; a++){
for(var b = 0; b < sourceProperties.length; b++ ){
if (collection[a].hasOwnProperty(sourceProperties[b])&&
collection[a].sourceProperties[b] === source.sourceProperties[b]){
arr.push(collection[a]);
}
}
}
// Only change code above this line
return arr;
}
whereAreYou([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
ummm what am i doing wrong ?
almy91 sends brownie points to @radascript :sparkles: :thumbsup: :sparkles:
:star: 311 | @radascript | http://www.freecodecamp.com/radascript
okay so i figured it out. yes, you did need to parse but your console.log was what was giving you the error for improper syntax. so all you actually need to write is
while(change>=0.01 && pennies>0)
{
ansPennies+=0.01
parseFloat(ansPennies.toFixed(2));
pennies-=0.01;
change-=0.01;
}
BUT when you had:
console.log(ansPennies = " old PENNIES");
// should be console.log(ansPennies + " old PENNIES");
is when you get the error value.toFixed() is not a function. the =
operator in there instead of +
was the culprit. sorry had to figure this one out, was bugging me lol. @Radascript
// Setup
var myArray = [];
// Only change code below this line.
var i=0 ;
while(i<5) {myArray.push(i); i++;}
// Setup
var myArray = [];
// Only change code below this line.
var i=0 ;
while(i<5) {myArray.push(i); i++;}
almy91 sends brownie points to @iamnawa :sparkles: :thumbsup: :sparkles:
:star: 426 | @iamnawa | http://www.freecodecamp.com/iamnawa
/[\W_]/g
this will include all non alpha numeric characters+ underscore, does this include space.
sameershamsudheen sends brownie points to @tenkdayz :sparkles: :thumbsup: :sparkles:
:star: 393 | @tenkdayz | http://www.freecodecamp.com/tenkdayz
hello i was doing check for Palindromes in Basic Algorithm, how do i print the value of string2 and string3 in the console, i used
console.log(string2);
but it is not working, help me please. here is my code
```
function palindrome(str) {
// Good luck!
var expression = /\W\s/g;
var string1 = str.replace(expression);
var string2 = string1.toLowerCase();
console.log(string2);
var string3 = function reverse(string2){
return string2.split("").reverse().join("");
};
if(string3 === str){
return true;
}
else {
return false;
}
}
palindrome("eye");``` @iAmNawa not working in my code
console.log()
causing the error, when in fact, it was your incorrect use of curly braces that was causing the error.
function whereAreYou(collection, source) {
// What's in a name?
var arr = [];
var sourceProperties = Object.keys(source);
// Only change code below this line
for(var a = 0;a < collection.length; a++){
for(var b = 0; b < sourceProperties.length; b++ ){
if (collection[a].hasOwnProperty(sourceProperties[b])&& collection[a][sourceProperties[b]] === source[sourceProperties[b]]){
arr.push(collection[a]);
}
}
}
// Only change code above this line
return arr;
}
whereAreYou([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
var string1 = str.replace(expression);
is this wrong
//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
if(firstName===contacts[firstName]) {
if(prop===[firstName].hasownprop) {return contacts[prop];}
else {return "No such property";}}
else {return "No such contact";}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
That i understand but do i need to use these as conditions 1 "Hole-in-one!"
<= par - 2 "Eagle"
par - 1 "Birdie"
par "Par"
par + 1 "Bogey"
par + 2 "Double Bogey"
= par + 3 "Go Home!"
var string1 = str.replace(expression, '');
var string3 = string2.split('').reverse().join('');
right or wrong
function printAlert() {
for (var i = 0; i < winCombs.length; i++) {
var str = winCombs[i].toString();
var regex = new RegExp(',', 'g');
//replace via regex
str = str.replace(regex, '');
for (var j = 0; j < output.length; j++) {
var testit = output[j].toString();
testit = testit.replace(regex, '');
if (str == testit) {
alert("Computer Won. The evil electric power!");
setTimeout(function() { location.reload(true) }, 4000);
} else if (arrComp.length === 5){
alert("Draw! You are good believe me.");
setTimeout(function() { location.reload(true) }, 4000);
}
}
}
}
challange split strings with split
var string = "Split me into an array";
var array = [];
// Only change code below this line.
array = string.split("\s");
what I'm dooing wrong?
split(/\s/)
:star: 1296 | @bkinahan | http://www.freecodecamp.com/bkinahan
ydeepk sends brownie points to @bkinahan :sparkles: :thumbsup: :sparkles:
var string1 = str.replace(/\W*\s+/g, '');
do this code remove all non-alphanumeric characters and all spaces from the string str
function palindrome(str) {
// Good luck!
var string1 = str.replace(/\W*/g, '');
var string2 = string1.toLowerCase();
var string3 = string2.split('').reverse().join('');
if(string3 === str){
return true;
}
else {
return false;
}
}
palindrome("eye");
alert
, since some people find those annoying :)
shivamarora13 sends brownie points to @bkinahan :sparkles: :thumbsup: :sparkles:
:star: 1297 | @bkinahan | http://www.freecodecamp.com/bkinahan
*
means "match between zero and unlimited times", so \W* might not work very well
/\W/g
instead, but that still doesn't account for the underscore character _
so you will have to consider that too
var string1 = str.replace(/\W\_/g, '');
any other errors
_
because it's not a special character. your regex matches an underscore after a non-word character, so you need or
in between them using |
Test regex here: https://regex101.com/
function fearNotLetter(str) {
var newArr = str.split("");
if (newArr[0] !== "a") {
return undefined;
}
for (i=0;i<newArr.length;i++) {
if (newArr[i].charCodeAt() < newArr[i+1].charCodeAt());
{ return newArr[i];
}
}
}
function fearNotLetter(str) {
var newArr = str.split("");
if (newArr[0] !== "a") {
return undefined;
}
for (i=0;i<newArr.length;i++) {
if (newArr[i].charCodeAt() > newArr[i+1].charCodeAt())
{ return newArr[i];}
}
}
function fearNotLetter(str) {
var newArr = str.split("");
if (newArr[0] !== "a") {
return undefined;
}
for (i=0;i<newArr.length;i++) {
if (newArr[i].charCodeAt() !== (newArr[i+1].charCodeAt()+1))
{ return newArr[i];}
}
}
function fearNotLetter(str) {
var newArr = str.split("");
if (newArr[0] !== "a") {
return undefined;
}
for (var i=0;i<newArr.length;i++) {
if (newArr[i].charCodeAt() +1 !== (newArr[i+1].charCodeAt()))
{ var getting = newArr[i].charCodeAt()+1;
return getting;}
}
}
String.fromCharCode()
is your friend.
if (newArr[0] !== "a")
looks like you are hard-coding test cases... (remove that line, you already return undefined
if you don't explicitly return from your function)
undefined
, for example by not using return
after that loop :P
function whereAreYou(collection, source) {
// What's in a name?
var arr = [];
var sourceProperties = Object.keys(source);
// Only change code below this line
for(var a = 0;a < collection.length; a++){
for(var b = 0; b < sourceProperties.length; b++ ){
if (collection[a].hasOwnProperty(sourceProperties[b])&& collection[a][sourceProperties[b]] === source[sourceProperties[b]]){
arr.push(collection[a]);
}
}
}
// Only change code above this line
return arr;
}
whereAreYou([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
for (var i = 0; i < str.length -1; i++) {
if (str.charCodeAt(i)+1 != str.charCodeAt(i+1)) {
return str[i];
}
}
return;
or an implicit return by reaching the function end both count as return undefined;
str.charCodeAt(i)
instead of newArr[i].charCodeAt()
, and check whether str.charCodeAt(i)+1 !== str.charCodeAt(i+1)
?
String.fromCharCode
, as it is the missing character you need to return, but other than that, yes, code looks fine :)
Does anyone know if I can pass a function straight in to
navigator.geolocation.getCurrentPosition( examplefunc (pos));
because I cant get it to work ?
I have had to use an anon func to call it ?
navigator.geolocation.getCurrentPosition( function(pos) { examplefunc(pos) });
function examplefunc(pos) {
// your code
}
navigator.geolocation.getCurrentPosition(examplefunc);
naassi sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star: 1645 | @blauelf | http://www.freecodecamp.com/blauelf
function orbitalPeriod(arr) {
var GM = 398600.4418;
var earthRadius = 6367.4447;
var pi = 3.1416;
var mul = Math.sqrt( earthRadius + Math.pow(arr[0].avgAlt,3)/GM );
var ans = 2*pi*mul;
return Math.round(ans);
}
earthRadius +
in the Math.pow, it adds to avgAlt.
if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(getWeather);
} else {
alert("Could not access location;");
};
var getWeather = function(pos) {
$.get('http://api.openweathermap.org/data/2.5/weather?lat=' + pos.coords.latitude +
'&lon=' + pos.coords.longitude + '&units=metric&APPID=f4bb493881267d09c5847a375103e72', function(data) {
$('.location').text(data.name);
$('.description').text(data.weather[0].description);
$('.temp').text(Math.round(data.main.temp) + "°C");
console.log(data);
});
}
function factorialize(num) {
var counter = 1;
while(num >= counter) {
num *= (num-1);
counter++;
}
return num;
}
factorialize(5);
@Zerazera function factorialize(num) {
while(num >= 1) {
num *= (num-1);
num--;
}
return num;
}
factorialize(5);
omiq17 sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star: 1646 | @blauelf | http://www.freecodecamp.com/blauelf
```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
broc93 sends brownie points to @negyvenketto :sparkles: :thumbsup: :sparkles:
:star: 365 | @negyvenketto | http://www.freecodecamp.com/negyvenketto
function lookUpProfile(firstName, prop){
var f = false;
var p = false;
for (var i = 0; i<contacts.length; i++){
if (contacts[i].firstName==firstName){
f = true;
if (contacts[i][prop]===""){
return "No such property";
} else return contacts[i][prop];
}
}
if (!f) return "No such contact";
}
lookUpProfile("Akira", "address"); should return "No such property" but instead it returns nothing. Why?
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
switch (val) {
case a:
answer = "apple";
break;
case b:
answer = "bird";
break;
case c:
answer = "cat";
break;
default:
answer = "stuff";
}
// Only change code above this line
return answer;
}
// Change this value to test
switchOfStuff(c);
"a"
(string literal of letter a), not a
(variable of name a)
switchOfStuff(c)
?
broc93 sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star: 1647 | @blauelf | http://www.freecodecamp.com/blauelf
Hi, I am working on the Intermediate Algorithm Scripting assignment that is about summing all primate numbers up to a given number. Here's the code:
function sumPrimes(num) {
//checks if a number is a prime, works correctly
function checkIfPrime(n) {
for (i = 2; i < n; i++) {
if (n % i === 0) {
return false;
} else if (i + 1 == n){
return true;
}
}
}
var primes = [];
for (j = 2; j <= num; j++) {
console.log('j = ' + j + ', num = ' + num); //logs correctly for each loop
if (checkIfPrime(num)) { /in this loop nothing gets executed
console.log(j);
primes = primes.push(num);
console.log(primes);
}
}
console.log('Im here');
/*
primes.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
});
*/
}
sumPrimes(10);
Could someone please help? I'm tottaly stuck. I have no idea why the for loop does not get executed (why the condition is never passed)
switchOfStuff("x")
?
/in this loop nothing gets executed
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
function switchOfStuff(val) {
var answer = "";
// Only change code below this line
switch (val) {
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;
default:
answer = "stuff";
}
// Only change code above this line
return answer;
}
// Only change code above this line
return answer;
}
// Change this value to test
switchOfStuff("a");
var
(might prevent some surprises, as undeclared variables might be global if not declared in some scope between).return true;
outside your loop instead of inside.
```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
return true
outside of the loop?
function checkIfPrime(n) {
for (i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
}
var
in front of i
for not making a global variable)
mtmorawska sends brownie points to @negyvenketto :sparkles: :thumbsup: :sparkles:
:star: 366 | @negyvenketto | http://www.freecodecamp.com/negyvenketto
function replacer(match) {
return match; // got '$&'
}
"&<>'".replace(/[&<>"']/gi, replacer('$&') );// got "&<>'"
//but
"&<>'".replace(/[&<>"']/gi, '$&'); // got "&<>'"
mtmorawska sends brownie points to @negyvenketto :sparkles: :thumbsup: :sparkles:
:warning: mtmorawska already gave negyvenketto points
"&<>'".replace(/[&<>"']/gi, replacer)
like this? replacer will be called with a couple of arguments, but the first is the whole match (followed by groups, then I think some start index and the whole string, but that's in the documentation of replace
cvdeby sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star: 1648 | @blauelf | http://www.freecodecamp.com/blauelf
Thanks to @Chrono79 for dictionary)
var dictionary = {
'&' : '&',
'<' : '<',
'>' : '>',
'"' : '"',
"'" : '''
};
function replacer(match) {
return dictionary[match];
}
function convertHTML(str) { return str.replace(/[&<>"']/gi, replacer );
}
Can I make it directly -without dictionary?
cvdeby sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star: 403 | @chrono79 | http://www.freecodecamp.com/chrono79
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[i].length ; i++)
if(firstName===contacts[i][firstName]) {
if(prop===contacts[i][firstName].hasownprop(prop)) {return contacts[i][prop];}
else {return "No such property";} }
else {return "No such contact";}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
&
instead, if it'll be needed in real project)
contacts[i].firstName
or contacts[i]["firstName"]
(as firstName is not a property name but the value to compare to, but "firstName" is the name)
else {}
around that last return statement.
ceasars
ceasars cipher
:triangular_flag_on_post: Remember to use Read-Search-Ask
if you get stuck. Try to pair program. :busts_in_silhouette: Write your own code. :memo:
- You need to write a function, which will take string encoded with
Caesar cipher as a parameter and decode it.- The one used here is ROT13 where the value of the letter is
shifted by 13 places.
e.g. 'A' ↔ 'N', 'T' ↔ 'G'.- You have to shift it back 13 positions, such that 'N' ↔ 'A'.
:pencil: read more about algorithm caesars cipher on the FCC Wiki
//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(firstName===contacts[i][firstName]) {
if(prop===contacts[i][firstName].hasOwnProp(prop)) {return contacts[i][prop];}
else {return "No such property";} }
else {return "No such contact";}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
for
loop.
for (var i=0;i< contacts.length ; i++) {
if(firstName===contacts[i][firstName]) {
if(prop===contacts[i][firstName].hasOwnProp(prop)) {return contacts[i][prop];}
else {return "No such property";} }
else {return "No such contact";}
}
$.ajax({
url: 'http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=json&lang=en',
success: function(data){
console.log("success ",data);
},
error: function(data){
console.log("error ",data);
},
type: 'GET'
});
this request providing proper response in postmaster but not in ajax call please guys help mefunction truncateString(str, num) {
// Clear out that junk in your trunk
return str.slice(0, num);
}
truncateString("A-tisket a-tasket A green and yellow basket", 11);
//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(firstName===contacts[i][firstName]) {
if(prop===contacts[i][firstName].hasOwnProp(prop)) {return contacts[i][prop];}
else {return "No such property";} }
else {return "No such contact";}}