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 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!";}
return (par,strokes);
:bulb: to format code use backticks! ``` more info
function confirmEnding(str, target) {
if ( str.substr((str.length - target.length), target.length) === target) { return true; } else {
return false;
}
}
confirmEnding("Bastian dog", "dog");
so happy
lanceward410 sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4293 | @chrono79 |http://www.freecodecamp.com/chrono79
function repeatStringNumTimes(str, num) {
// repeat after me
var longstr = "";
while (num > 0) {
num--;
longstr += str;
}
return longstr;
}
repeatStringNumTimes("abc", 3);
var longStr="";
for(var i=0;i<num;i++)
{
longStr+=str;
}
return longStr;
@Lanceward410
Now if someone writes code without ever hitting Enter.... THAT is messy
it's called minified I think
//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
var i = 0;
while(i < contacts.length) {
if (firstName == contacts.firstName) {
if (prop == contacts.hasOwnProperty(prop)) {
return contacts[prop];
} else if (prop != contacts.hasOwnProperty(prop)) {
return "No such property";
} else if (firstName != contacts.firstName) {
return "No such contact";
}
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
rollinsons sends brownie points to @longnt80 and @lanceward410 :sparkles: :thumbsup: :sparkles:
:cookie: 380 | @longnt80 |http://www.freecodecamp.com/longnt80
:cookie: 252 | @lanceward410 |http://www.freecodecamp.com/lanceward410
contacts[i]
<- like that$(document).ready(function() {
function codeAddress() {
var changeTemp = document.getElementById("CtoF").innerHTML;
console.log(changeTemp);
window.onload = codeAddress;
$("#CtoF").on("click", function() {
if (changeTemp === "℃") {
changeTemp = "℉";
} else {
changeTemp = "℃";
}
document.getElementById("CtoF").innerHTML = changeTemp;
console.log(changeTemp);
});
}
var cityName = $("#weatherSearch").val();
var key = "d1533e8cd0767e04eca3f7b99ffe166a";
$("#weatherMe").on("click", function() {
console.log(cityName);
$.getJSON('http://api.openweathermap.org/data/2.5/weather?' + '&q=' + cityName + '&APPID=' + key, function(json) {
var TempInKelvin = json.main.temp;
console.log(TempInKelvin);
var Pressure = json.main.pressure;
console.log(Pressure);
var Humadity = json.main.humidity;
console.log(Humadity);
var MinTempInKelvin = json.main.temp_min;
console.log(MinTempInKelvin);
var MaxTempInKelvin = json.main.temp_max;
console.log(MaxTempInKelvin);
// var Condition = [];
var Condition = json.weather[0].description;
console.log(Condition);
var image = new Image();
image.src = "Temp.jpg";
image.height = 100;
image.width = 100;
if (TempInKelvin === '') {
TempInKelvin = 'unknown';
} else if (changeTemp === "℃") {
var TemInCelcius = TempInKelvin - 273.15;
$(".temp").append(image, +TemInCelcius + "℃");
} else {
var TempInFahrenheit = ((9 / 5) * (TempInKelvin - 273) + 32);
$(".temp").append(image, +TempInFahrenheit + "℉");
}
});
});
});
@Chrono79
Plesae consider this one
$(document).ready(function() {
var changeTemp = document.getElementById("CtoF").innerHTML;
console.log(changeTemp);
window.onload = codeAddress;
$("#CtoF").on("click", function() {
if (changeTemp === "℃") {
changeTemp = "℉";
} else {
changeTemp = "℃";
}
document.getElementById("CtoF").innerHTML = changeTemp;
console.log(changeTemp);
});
var cityName = $("#weatherSearch").val();
var key = "d1533e8cd0767e04eca3f7b99ffe166a";
$("#weatherMe").on("click", function() {
console.log(cityName);
$.getJSON('http://api.openweathermap.org/data/2.5/weather?' + '&q=' + cityName + '&APPID=' + key, function(json) {
var TempInKelvin = json.main.temp;
console.log(TempInKelvin);
var Pressure = json.main.pressure;
console.log(Pressure);
var Humadity = json.main.humidity;
console.log(Humadity);
var MinTempInKelvin = json.main.temp_min;
console.log(MinTempInKelvin);
var MaxTempInKelvin = json.main.temp_max;
console.log(MaxTempInKelvin);
// var Condition = [];
var Condition = json.weather[0].description;
console.log(Condition);
var image = new Image();
image.src = "Temp.jpg";
image.height = 100;
image.width = 100;
if (TempInKelvin === '') {
TempInKelvin = 'unknown';
} else if (changeTemp === "℃") {
var TemInCelcius = TempInKelvin - 273.15;
$(".temp").append(image, +TemInCelcius + "℃");
} else {
var TempInFahrenheit = ((9 / 5) * (TempInKelvin - 273) + 32);
$(".temp").append(image, +TempInFahrenheit + "℉");
}
});
});
});
.split(" ")
will break your string up into an array of words. I can't really give you the answer, but that is a basic outline of a solution
arr[0]
is the first word in the string. arr[1]
is the second word. You will replace this with arr[i]
in your for loop to indicate that your code is going to run on each word in the array one by one.
function findLongestWord(str) {
var splitString = str.split(' ');
var longestWord = 0;
for ( i=0; i <= splitString.length; i++ )
if (splitString.length > longestWord) {
return splitString.length;
}
else { return longestWord;
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
longestWord = splitArray[i];
splitString[i].length
, I'm sorry
:bulb: to format code use backticks! ``` more info
function findLongestWord(str) {
var splitString = str.split(' ');
var longestWord = 0;
for ( i=0; i < splitString.length; i++ ) {
if (splitString[i].length > longestWord) {
splitString[i] = longestWord;
} else {
return longestWord;
}
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function findLongestWord(str) {
var splitString = str.split(' ');
var longestWord = 0;
for ( i=0; i < splitString.length; i++ ) {
if (splitString[i].length > longestWord) {
splitString[i] = longestWord;
} else {
return longestWord;
}
}
}
findLongestWord("The quick brown fox jumped over the lazy dog");
$("#inCelsius").click(function(){
$("#temperature").html(tempInCelsius+"°C");
});
rollinsons sends brownie points to @pahosler :sparkles: :thumbsup: :sparkles:
:cookie: 373 | @pahosler |http://www.freecodecamp.com/pahosler
x = 2
. Do NOT write 2 = x
function findLongestWord(str) {
var longestWord = 0;
var splitString = str.split(' ');
for ( i=0; i < splitString.length; i++ ) {
if (splitString[i].length > longestWord.length) {
longestWord = splitString[i].length;
}
}
return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
href
on a <a>
tag but i get the following error
Unsafe JavaScript attempt to initiate navigation for frame with URL 'https://www.wikipedia.org/' from frame with URL 'https://s.codepen.io/boomerang/iFrameKey-8327d59c-11ad-7f21-c76a-6604a4156689/index.html?editors=1011'. The frame attempting navigation is sandboxed and is trying to navigate a popup, but is not the popup's opener and is not set to propagate sandboxing to popups.
erichasegawa sends brownie points to @lanceward410 and @sjames1958gm :sparkles: :thumbsup: :sparkles:
:cookie: 254 | @lanceward410 |http://www.freecodecamp.com/lanceward410
:star2: 7782 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
target="_blank"
in your <a>apravink sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 7783 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
var count = 0;
function cc(card) {
// Only change code below this line
switch (card){
case 2:
case 3:
case 4:
case 5:
case 6:
count ++;
break;
case 10:
case 'J':
case "Q":
case 'K':
case 'A':
count --;
break;
}
if (count > 0 ){
return count +"Bet";
}else {
return count +"Hold";
}
‛‛‛ function golfScore(par, strokes) {
// Only change code below this line
return "Change Me";
// Only change code above this line
}
// Change these values to test
golfScore(5, 4); ‛‛‛
Mixed Content: The page at 'https://codepen.io/abhiwan/pen/VWaXNv?editors=1011' was loaded over HTTPS, but requested an insecure resource 'http://en.wikipedia.org/?callback=?&curid=45692901'. This request has been blocked; the content must be served over HTTPS.
apravink sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:warning: apravink already gave sjames1958gm points
count + "bet";
Your final answer would come out as "5bet". You want to make it so there's a space in between the count and the decision.
mackyking sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 7784 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
@mackyking
if (condition) {
return "String";
} else if (condition) {
}
where the conditions are the comparisons of strokes to par.
Return the appropriate "String"
var count = 0;
function cc(card) {
// Only change code below this line
switch (card){
case 2:
case 3:
case 4:
case 5:
case 6:
count ++;
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count --;
break;
}
if (count > 0 ){
return count + "Bet";
}else {
return count + "Hold";
}
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
"Bet"
and "Hold"
quotes. It's very case sensitive and only what is within the quotes will be returned in the string
"Hello" + " " + "World"
equals "Hello World"
fmccroy sends brownie points to @thekholm80 :sparkles: :thumbsup: :sparkles:
:star2: 1074 | @thekholm80 |http://www.freecodecamp.com/thekholm80
&callback=?
to your URL
function nextInLine(arr, item) {
arr.push(item);
arr.shift(0);// 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, 1)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));
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
}
}
}
// Only change code above this line
// Change these values to test your function
lookUpProfile("Akira", "likes");
@ottocedeno
You can assign the return from arr.shift() to item since you return item
arr.shift(0);// Your code here
return item; // Change this line
or replace the above with
return arr.shift();
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 && contacts[i][prop] === true){
console.log(contacts[i][prop]);
}else if(contacts[i]["firstName"] === firstName && contacts[i][prop]=== false ){
console.log('No such property');
}else{
console.log('No such contact');
}
}
}
// Only change code above this line
// Change these values to test your function
lookUpProfile("Akira", "likes");
contacts[i][prop] === true
<- that's wrong#252 Caesars Cipher
In String.fromCharCode(num1[, ...[, numN]]), all these numbers can be in an array? Will it return same?
Or do I need to store it in by for loop for each array element and join('')?
var code_old=[]; //Storing old alphabet codes in code_old
for (var i=0; i < str.length; i++) {
code_old[i]=str.charCodeAt(i);
} //Changing ONLY alphabets code by reducing 13 else unchanged
for (i=0;i<str.length;i++){
if(code_old[i] > 64 && code_old[i] < 92)
code_old[i] -= 13;
else
code_old[i] -= 0;
}
var str2;
return str2.fromCharCode(code_old);
//var arr;
//var a;
//for (i=0;i<str.length;i++){
//a=str2.fromCharCode(code_old.shift());
//arr.push(str2.fromCharCode(code_old.shift()));
//}
//return arr.join('');
// return newstr;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
mthinh sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4294 | @chrono79 |http://www.freecodecamp.com/chrono79
var arr = [1, 2, 3];
console.log(...arr); // 1, 2, 3
String.fromCharCode(...arr);
'esversion: 6';
at the top
var reg=/[&<>"']/gi;
var re={"&":"&",
"<":"<",
">":">",
"\"":""",
"\'":"'"
};
return str.replace(reg,re[reg]);
var reg=/[&<>"']/gi;
var re={"&":"&",
"<":"<",
">":">",
"\"":""",
"\'":"'"
};
return str.replace(reg,re[reg]);
re[reg]
that's the problem. wait let me run it.
@Chrono79 function lookUpProfile(firstName, prop){
// Only change code below this line
for(var 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';
}
} else{
return 'No such contact';
}
}
}
reg
is your regex not the property name :)
@fillopfy put the callback method at the
replace( ... , (match)=>{
console.log(match);
})
try to do that
replace( ... , function(match) {
console.log(match);
})
=>
that is a arrow function, ES6 syntax, forget it stick with older one :)
match
as your property name.
if (strokes == someValue) {
return "someString";
} else if ...
piyush805 sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4295 | @chrono79 |http://www.freecodecamp.com/chrono79
function lookUpProfile(firstName, prop){
// Only change code below this line
for(var 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';
}
}
}
}
mthinh sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:warning: mthinh already gave chrono79 points
var value = 1;
function factorialize(num) {
if(num<1){
return value;
}else{
for(i=num; i>0; i--){
num = value *=i;
}
return num;
}
}
factorialize(0);
value
should be inside of your function.
but @revisualize did you read that :
Hi @revisualize
The issue tracker is for reporting bugs only. If this is a request for help with a challenge, please use the help chat room or try looking through the forum for help with a specific challenge.
If this is the case, please close this issue.
Happy Coding.
function truncateString(str, num) {
// Clear out that junk in your trunk
if (str.length >= num) {
str = str.substring(0, num-3);
return str + "...";
}
else {
return false;
}
}
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length);
forwebtech sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4296 | @chrono79 |http://www.freecodecamp.com/chrono79
process.stdin.on('data', function(chunk) {
let input = Buffer.from(chunk).toString().replace(/[\r\n]/g, '');
console.log(chunk);
if(input === 'exit') {
process.stdin.end();
setTimeout(function() {
}, 2000);
}
});
myObj === true
that part is wrong
checkProp.myObj
is wrong too (for 2 reasons)
// Setup
function phoneticLookup(val) {
var result = "";
// Only change code below this line
var lookup = {
"alpha" : "Adams",
"bravo": "Boston",
"charlie": "Chicago",
"delta" : "Denver",
"echo" : "Easy",
"foxtrot" : "Frank",
};
// Only change code above this line
return result;
};
// Change this value to test
phoneticLookup("charlie");
val=
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS Drum Kit</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="keys">
<div data-key="65" class="key">
<kbd>A</kbd>
<span class="sound">clap</span>
</div>
<div data-key="83" class="key">
<kbd>S</kbd>
<span class="sound">hihat</span>
</div>
<div data-key="68" class="key">
<kbd>D</kbd>
<span class="sound">kick</span>
</div>
<div data-key="70" class="key">
<kbd>F</kbd>
<span class="sound">openhat</span>
</div>
<div data-key="71" class="key">
<kbd>G</kbd>
<span class="sound">boom</span>
</div>
<div data-key="72" class="key">
<kbd>H</kbd>
<span class="sound">ride</span>
</div>
<div data-key="74" class="key">
<kbd>J</kbd>
<span class="sound">snare</span>
</div>
<div data-key="75" class="key">
<kbd>K</kbd>
<span class="sound">tom</span>
</div>
<div data-key="76" class="key">
<kbd>L</kbd>
<span class="sound">tink</span>
</div>
</div>
<audio data-key="65" src="sounds/clap.wav"></audio>
<audio data-key="83" src="sounds/hihat.wav"></audio>
<audio data-key="68" src="sounds/kick.wav"></audio>
<audio data-key="70" src="sounds/openhat.wav"></audio>
<audio data-key="71" src="sounds/boom.wav"></audio>
<audio data-key="72" src="sounds/ride.wav"></audio>
<audio data-key="74" src="sounds/snare.wav"></audio>
<audio data-key="75" src="sounds/tom.wav"></audio>
<audio data-key="76" src="sounds/tink.wav"></audio>
<script>
window.addEventListener('keydown', function(e) {
// const audio = document.querySelector(`audio[data-key=${e.keycode}]`)
console.log(e.keycode)
});
</script>
</body>
</html>
i dont know how to use the loop to give me the correct values of my properties;
When i console.log that return for the loop, it gives me the value of the 4 properties of likes,
//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++){
return contacts[i][prop];
}
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
if u not sure.. then... console.log(e)
and inspect console
keyCODE
is NOT the same as keycode
neither keyCode
keyCode
property not keycode
marioc3 sends brownie points to @lumexralph :sparkles: :thumbsup: :sparkles:
:star2: 1937 | @lumexralph |http://www.freecodecamp.com/lumexralph
1. you need a loop to pick each objects in the contacts array
1.1 in the loop you need to
1.1.1 check if the objects picked has the firstName property equal to the firstName parameter
1.1.1.1 you need to check if it has a property prop
return the value of prop in the object
1.1.1.2 return no such property if 1.1.1.1 is false
2. when your loop is done looking through contacts return no such contact
fdemaa sends brownie points to @lumexralph :sparkles: :thumbsup: :sparkles:
:star2: 1938 | @lumexralph |http://www.freecodecamp.com/lumexralph
e
event object from your devTool console, then you'll come across the property you're trying to access
fdemaa sends brownie points to @codersc :sparkles: :thumbsup: :sparkles:
:cookie: 264 | @codersc |http://www.freecodecamp.com/codersc
fahrenheit
:bulb: to format code use backticks! ``` more info
fahrenheit = celsius * 9 / 5 + 32;
\"
Object.hasOwnProperty(property);
Object.hasOwnProperty(props)
Object
is the object you want to check
\\
?
betanya sends brownie points to @moigithub :sparkles: :thumbsup: :sparkles:
:star2: 3371 | @moigithub |http://www.freecodecamp.com/moigithub
lerithapride1 sends brownie points to @lumexralph :sparkles: :thumbsup: :sparkles:
:star2: 1939 | @lumexralph |http://www.freecodecamp.com/lumexralph
celsius = (-10);
celsius = (-30);
.
at the end there.
click run tests first
//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"==firstName && (contacts).hasOwnProperty(prop)){
for(i=0; i<contacts.length; i++){
return contacts[i][prop];
}
}
}
// Change these values to test your function
lookUpProfile("Akira", "adress");
\"
contacts
array.
fdemaa sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4272 | @masd925 |http://www.freecodecamp.com/masd925
var myStr; // Change this line
var myStr = "First\tLine\n\"Second\tLine\"\rThird\tLine";
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str.replace(/ |_|([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
spinalCase('AllThe-small Things');
can someone explain the '$1-$2' here?
var myStr = "FirstLine\n\\SecondLine\\\rThirdLine";
([a-z])([A-Z])
are capturing groups - $1 and $2 are the first and second captured values from your regex matches
([a-z])
wonder2991 sends brownie points to @cmccormack and @ivancsicsmarkus :sparkles: :thumbsup: :sparkles:
:cookie: 620 | @ivancsicsmarkus |http://www.freecodecamp.com/ivancsicsmarkus
:cookie: 911 | @cmccormack |http://www.freecodecamp.com/cmccormack
zayn1914 sends brownie points to @ivancsicsmarkus :sparkles: :thumbsup: :sparkles:
:cookie: 621 | @ivancsicsmarkus |http://www.freecodecamp.com/ivancsicsmarkus
function sumFibs(num) {
serie = [1,1];
sum = 0;
stop = false;
counter = 1;
while ( !stop ){
if(num == 1 || num == 2){
serie = [1,1];
stop = true;
}else{
serie.push(serie[counter-1] + serie[counter]);
counter++;
console.log('num', num);
console.log('serie',serie);
if(num <= serie[serie.length-1]){ stop = true; }
}
}
return serie.reduce(
function(accumulator,acctualValue){
// si es par pasa solo el accumulator else suma accumulator y acctualValue
console.log("serie",serie);
return ( acctualValue%2 === 0 ) ? accumulator : accumulator + acctualValue;
},0);
}
sumFibs(4);
Sup, friends. Strugglin here, not sure how to tell these nested for loops to check for more than one value in each array.
'''
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product = product * arr[i]
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1],[2],[3]]);
'''
:bulb: to format code use backticks! ``` more info
function sumFibs(num) {
serie = [1,1];
sum = 0;
stop = false;
counter = 1;
while ( !stop ){
if(num == 1 || num == 2){
serie = [1,1];
stop = true;
}else{
serie.push(serie[counter-1] + serie[counter]);
counter++;
console.log('num', num);
console.log('serie',serie);
if(num < (serie[serie.length-1] + serie[serie.length-2])){ stop = true; }
}
}
//return serie;
return serie.reduce(
function(accumulator,acctualValue){
// si es par pasa solo el accumulator else suma accumulator y acctualValue
console.log("serie",serie);
return ( acctualValue%2 === 0 ) ? accumulator : accumulator + acctualValue;
},0);
}
sumFibs(4);
arr[j]
?
alejandrlara12 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:cookie: 912 | @cmccormack |http://www.freecodecamp.com/cmccormack
arr[j]
``
function reverseString(str) {
var array = str.split("");
var newArray = array.reverse();
var finalArray = newArray.join("");
return finalArray;
}
reverseString("hello");``
poncatoera sends brownie points to @alejandrlara12 :sparkles: :thumbsup: :sparkles:
:cookie: 250 | @alejandrlara12 |http://www.freecodecamp.com/alejandrlara12
product
by each number in the array, even if there are sub-arrays. e. g. [[1, 2], [3, 4], [5, 6, 7]]
'Hello, World!'.split('').map((v,i,a)=>a[-i+a.length-1]).join('')
function chunkArrayInGroups(arr, size) {
// Break it up.
var result = [];
return result;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
need help for chunky monkey challenge.. How do i slice array at every given size
interval?
product
by the number in position j
in the array, so long as j
is less than the length of the sub-array at position i
. my next step is to keep looping until it exhausts all the numbers in each sub-array, right?
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product = product * arr[j];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1, 2],[3, 4],[5, 6, 7]]);
product = product*arr[i][j];
TypeError: Cannot read property 'length' of undefined
. my code:function largestOfFour(arr) {
// You can do this!
largestArr = [];
for (var i = 0; i <= arr.length; i++){
for (var j = 0; j<= arr[i].length; j++){
if (arr[i][j] < largestArr[i]){
largestArr[i] = arr[i][j];
}
}
}
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
<=
on your loops - length is the number of items in the array, but array indexes start from 0
function rot13(str) { // LBH QVQ VG!
var arr = [];
console.log("@@ " + arr);
console.log(/^[a-zA-Z]+$/.test(str[0]));
for (i=0; i<str.length; i++) {
if (/^[a-zA-Z]+$/.test(str[i])) {
tmp = str.charCodeAt(i);
tmp += 13;
console.log("^^ " + tmp);
a = str[i];
console.log("~~ " + a);
arr.push(a.fromCharCode(tmp));
}
}
/* str = arr.join(" "); */
return str;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
function factorialize(num) {
if (num === 0) {
return 1;
} else {
var array = [];
for ( var i = 1; i <= num; i++){
array.push(i);
}
answer = array.reduce(function (previousVal, currentVal) {
return previousVal * currentVal;
}); return answer;
}
}
factorialize(5);
happyredditor59 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:cookie: 913 | @cmccormack |http://www.freecodecamp.com/cmccormack
roshambembo sends brownie points to @kpbro and @cmccormack :sparkles: :thumbsup: :sparkles:
:cookie: 253 | @kpbro |http://www.freecodecamp.com/kpbro
:cookie: 914 | @cmccormack |http://www.freecodecamp.com/cmccormack
function factorialize(num) {
if (num === 0) {
return 1;
} else {
var array = [];
for ( var i = 1; i <= num; i++){
array.push(i);
}
answer = array.reduce(function (previousVal, currentVal) {
return previousVal * currentVal;
}); return answer;
}
}
factorialize(5);
fromCharCode
is a String method, call String.fromCharCode(tmp)
poncatoera sends brownie points to @kpbro :sparkles: :thumbsup: :sparkles:
:cookie: 254 | @kpbro |http://www.freecodecamp.com/kpbro
@VinayVijayJoshi https://mdn.io/fromCharCode -
Because fromCharCode() is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.
size
interval?
@poncatoera
function factorialize(num) {
var factorial = 1;
for (i = 1; i <= num ; i++) {
factorial *= i;
}
return factorial;
}
factorialize(5);
No array needed
vinayvijayjoshi sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:cookie: 915 | @cmccormack |http://www.freecodecamp.com/cmccormack
poncatoera sends brownie points to @johnnybizzel :sparkles: :thumbsup: :sparkles:
:star2: 1708 | @johnnybizzel |http://www.freecodecamp.com/johnnybizzel
for(var i=0;i<arr.length;i++)
cmccormack sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2641 | @forkerino |http://www.freecodecamp.com/forkerino
i have to "Initialize the three variables a, b, and c with 5, 10, and "I am a" respectively so that they will not be undefined."
then i have here
var a = 5;
var b = 10;
var c = "i am a";
a = a + 1;
b = b + 5;
c = c + " String!";
but there's something wrong withc
"c should not contain undefined and should have a value of "I am a String!" "
function chunkArrayInGroups(arr, size) {
// Break it up.
var result = [];
for(var i=0;i<arr.length;i+size){
var sliced = arr.slice(i,size);
result.push(sliced);
}
return result;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
@forkerino
i
end index. but where to start?
i
and figure out where to end.
json.forEach(function(val) { //for each values in the json file
var keys = Object.keys(val); //keys is defined as the keys(id, imageLink, ...) in each values, where "values" is the stuff with { }
html += "<div class = 'cat'>";
keys.forEach(function(key) { //run a function with parameter "key" which is defined as the single items in "keys" (id, imageLink, ...)
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
i
and ended at i+size
kpbro sends brownie points to @masd925 and @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2642 | @forkerino |http://www.freecodecamp.com/forkerino
:star2: 4273 | @masd925 |http://www.freecodecamp.com/masd925
@Masd925 Can you help me?
Here is my thought about the above code. Can you tell me whether I get the point or not?
json.forEach(function(val) { //for each values in the json file
var keys = Object.keys(val); //keys is defined as the keys(id, imageLink, ...) in each values, where "values" is the stuff with { }
html += "<div class = 'cat'>";
keys.forEach(function(key) { //run a function with parameter "key" which is defined as the single items in "keys" (id, imageLink, ...)
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
@Masd925 Actually, the whole code is as follow
$(document).ready(function() {
$("#newQuoteButton").on("click", function(){
//$("blockquote").html("Here is the message");
// JSON LINK: https://api.myjson.com/bins/1by0m3
$.getJSON("https://api.myjson.com/bins/1by0m3", function(json){
var html = "";
json.forEach(function(val){
var keys = Object.keys(val);
html += "div class = 'quote'"
keys.forEach(function(key){
html = key + val[key] + "<br>";
});
html += "</div><br>";
});
$("p").html(html);
});
});
});
svg = d3.select("#visualBox")
.append("svg")
.attr("width", w)
.attr("height", h);
var bars = svg.selectAll("rect")
.data(dataSet)
.enter()
.append("rect")
.attr("class", "bar");
bars.attr("x", function(d, i) { return i * (w / dataSet.length); } );
bars.attr("y", function(d) {return h - scale(d.value); });
bars.attr("width", function(d) {return w / dataSet.length - padding; });
bars.attr("height", function(d) {return scale(d.value); });
bars.style("fill", function(d) {return color[d.state]; } );
I have this rectangular bars made using d3 js library. now how can I add text value to each of the rectagular bar?
json
is a JS array of quote objects. You can get a random quote by getting (and then accessing) a random element from that array.
var arr = [5,6,7,8];
arr[Math.floor(Math.random()*arr.length)];
TypeError: newStr.join is not a function
. this is my code:
function truncateString(str, num) {
// Clear out that junk in your trunk
var newStr = [];
if (str.length > num-3){
str = str.split('');
for (var i = 0; i < num-3; i++){
newStr += str[i];
}
newStr = newStr.join('') + "...";
str = newStr;
}
return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 11);
happyredditor59 sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2643 | @forkerino |http://www.freecodecamp.com/forkerino
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(var i=0;i<multiplyAll.length;i++){
for(var j=0;j<multiplyAll[i].length;j++){
product*=multiplyAll[i][j].length;
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]
arr
... multiplyAll is the function name
function confirmEnding(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
for (var i = 0; i < str.length; i++) {
if (str.substr(str.length-1) && str.substr(str.length-4) == target) {
return true;
} else {
return false;
}
}
return str;
}
confirmEnding("Bastian", "n");
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for(var i=0;i<arr.length;i++){
for(var j=0;j<arr[i].length;j++){
product*=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]]);
@forkerino
===
, so you can solve it without a loop by making a substring from str and comparing with target.
lucky73 sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2644 | @forkerino |http://www.freecodecamp.com/forkerino
var string = "Split me into an array";
var array = [];
// Only change code below this line.
array = string.split('');
manonja sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2645 | @forkerino |http://www.freecodecamp.com/forkerino
:bulb: to format code use backticks! ``` more info
function lookUpProfile(firstName, prop){
// Only change code below this line
for (i = 0; i < contacts.length; i++){
if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
else if (contacts[i].firstName !== firstName){
return "No such contact";
}
else if (contacts[i].hasOwnProperty(prop) !== true){
return "No such property";
}
}
// Only change code above this line
}
function destroyer(arr) {
// Remove all the values
for (var i = 0; i < arguments.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arguments[i] === arr[j]) {
arr.splice(arr[j], 1);
}
}
}
return arr;
}
var ourArray = [1,2,3];
ourArray[1] = 3; // ourArray now equals [1,3,3].
// Setup
var myArray = [3,2,3];
ourArray[0] = 3;
// Only change code below this line.
hi guys what's wrong
splice
inside a loop. Splice change the instance of the array, so you have no certainty that the second time it loops over you are looking at the "same" data as before
@shashank1999coder
ourArray[0] = 3;
You are changing ourArray
when you should change myArray
chinemelu sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4274 | @masd925 |http://www.freecodecamp.com/masd925
filter
already loop into the array and execute a function for every instance of it
shashank1999coder sends brownie points to @marmiz :sparkles: :thumbsup: :sparkles:
:cookie: 932 | @marmiz |http://www.freecodecamp.com/marmiz
dseillier sends brownie points to @marmiz :sparkles: :thumbsup: :sparkles:
:cookie: 933 | @marmiz |http://www.freecodecamp.com/marmiz
argument
object works
0
and 1
are logical results for many things, but why for example 5
:rat:
var arr = [1, 2, 3, 4, 5]
var filtered = arr.filter(function(value){
console.log(value) // so that you'll see in console that is looping into the array --> 1 - 2 -3 -4 -5
return val > 3
})
arr // [1, 2, 3, 4, 5]
filtered // [ 4, 5] only number > 3 has been returned
function destroyer(arr) {
// Remove all the values
var newArr = arr.filter(function(value) {
return value !== arguments;
});
return newArr;
}
!= arguments
arguments
is actually looking like?
dseillier sends brownie points to @marmiz :sparkles: :thumbsup: :sparkles:
:warning: dseillier already gave marmiz points
Can someone help me with the Exact Change Challenge? Some hints on how to go about it...?
https://www.freecodecamp.com/challenges/exact-change
anyonee???
cid
.
OSPF
model
```function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
var myNoun = "dog";
var myAdjective = "big";
var myVerb = "ran";
var myAdverb = "quickly";
result = "The " + myAdjective + " " + myNoun + " " + myVerb + " " + myAdverb + ".";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("cat", "little", "hit", "slowly");``` Doesn't pass the third test...
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
for(i in firstName){
if(contacts[i].firstName===firstName){
if(contacts[i].hasOwnProperty(prop)===true){
return contacts[i][prop];
} else {
return "No such property";
}
}
// Only change code above this line
}
}
}
I can't get the function to return the element that was removed in the "Stand In Line" exercise...
function nextInLine(arr, item) {
// Your code here
testArr.push(item);
testArr.shift();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
return contacts[prop]
instead
arr
and return arr.shift();
not item
aday091 sends brownie points to @lumexralph :sparkles: :thumbsup: :sparkles:
:star2: 1940 | @lumexralph |http://www.freecodecamp.com/lumexralph
contacts
is an array? Are you writing some type of code to iterate through the array, like a for
loop? And if you are, are you generating an index - you have to use that to access the array elements.
for ( var i = 0; i < contacts.length; i++ ) {
is the start of the loop that you want.
@kjuchtmans is discovering new toys: .hide()
and .show()
:baby:
who cares to give me feedback on my "Wikipedia Viewer"?
pen
it's working for me (notwithstanding the bland styling)
any tips welcome on e.g. :
would help me a lot! I'm slowly falling in love with jQuery
function factorialize(n) {
for(var i = 1; i < n+1; i++){
var resutl = n*(n-i);
return resutl;
}
}
factorialize(5);
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
result = "This " + myAdjective + " " + myNoun + " " + myVerb + " " + myAdverb +"!";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("exercise", "freeCodeCamp", "is", "Bullshit");
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
for(i in contacts){
if(contacts[i].firstName==firstName){
if(contacts[i].hasOwnProperty(prop)===true){
return contacts[i][prop];
} else {
return "No such property";
}
}
// Only change code above this line
}
}
}
if(contacts[i].prop!==prop){
return "No such contact";
}
javasctipt
javascript
function factorialize(n) {
for(var i = 1; i < n+1; i++){
var result = n*(n-i);
return result;
}
}
factorialize(10);
@pwadeveloper
look at mine
function lookUpProfile(firstName, prop){
var a;
for(var i=0;i<contacts.length;i++){
if (firstName===contacts[i].firstName && contacts[i].hasOwnProperty(prop)===true){
a= contacts[i][prop];
break;
}
else if(firstName!==contacts[i].firstName && contacts[i].hasOwnProperty(prop)===true){
a="No such contact";
}
else {
a= "No such property";
}
}
return a;
}
'''
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
result = "This " + myAdjective + " " + myNoun + " " + myVerb + " " + myAdverb +"!";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("exercise", "freeCodeCamp", "is", "Bullshit");
'''
:bulb: to format code use backticks! ``` more info
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
for(i in contacts){
if(contacts[i].firstName==firstName){
if(contacts[i].hasOwnProperty(prop)===true){
return contacts[i][prop];
} else {
return "No such property";
}
}
if(contacts[i].prop!==prop){
return "No such contact";
}
// Only change code above this line
}
}
}
@khaduch thanks for taking a look. yeah, even FCC example was not really interactive on nonsense strings; just did nothing. Wikipedia web search gives you meaningful alternatives in that case, but I'm a bit hesitant -if interested- to code out 'Did you mean...?' options.
Any thoughts on how this could be done?
kjuchtmans sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 2995 | @khaduch |http://www.freecodecamp.com/khaduch
firstName
property has the same value as the firstName
variable.
'''js
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
result = "This " + myAdjective + " " + myNoun + " " + myVerb + " " + myAdverb +"!";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("dog", "big", "ran", "fast");
'''
:bulb: to format code use backticks! ``` more info
'''js
function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
var result = "";
// Your code below this line
result = "This " + myAdjective + " " + myNoun + " " + myVerb + " " + myAdverb +"!";
// Your code above this line
return result;
}
// Change the words here to test your function
wordBlanks("exercise", "freeCodeCamp", "is", "Bullshit");
'''
:bulb: to format code use backticks! ``` more info
function factorialize(n) {
for(var i = 1; i < n+1; i++){
n = n*(n-i);
return n;
}
}
factorialize(10);
why my loop doesnt work ? pls
aday091 sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 2996 | @khaduch |http://www.freecodecamp.com/khaduch
arcteryx sends brownie points to @aday091 :sparkles: :thumbsup: :sparkles:
:cookie: 176 | @aday091 |http://www.freecodecamp.com/aday091
n
is the final value that you would want your loop to handle. A separate variable to accumulate your answer would mean that you keep n
as it is, and generate a result that you can then return.
function nextInLine(arr, item) {
// Your code here
testArr.push(item);
testArr.shift();
return arr.shift(); // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
testArr
. There are two function argument - arr
is the array that you should be working with. item
is the item that you should be adding to the array.
// This works with an IIFE
var budgetController = (function() {
var x = 23;
var add = function(a) {
return x + a;
}
return {
publicTest: function(b) {
console.log(add(b));
}
}
})();
budgetController.publicTest(5);
// Yet this does not work (without IIFE)
var budgetController = function() {
var x = 23;
var add = function(a) {
return x + a;
}
return {
publicTest: function(b) {
console.log(add(b));
}
}
};
budgetController(); // After this line, shouldn't var budgetController have access to publicTest?
budgetController.publicTest(5);
.shift()
twice in your code. You should only use it once...
.push()
and then return what you get from the .shift()
budgetController
is assigned the function publicTest
budgetController
is assigned with a function with no parameter
This code meets two of the four requirements
function nextInLine(arr, item) {
// Your code here
testArr.push(item);
testArr.shift();
return arr.shift(); // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
while this code meets the opposite two:
function nextInLine(arr, item) {
// Your code here
testArr.push(item);
testArr.shift();
return item; // Change this line
}
// Test Setup
var testArr = [1,2,3,4,5];
robmeador sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:star2: 2997 | @khaduch |http://www.freecodecamp.com/khaduch
arr
within the function. Take your first code block, change testArr
to arr
within the function. Then remove the line that currently says testArr.shift()
. Keep your return
line. See what happens.
function lookUpProfile(firstName, prop){
// Only change code below this line
for (var i=0; i<contacts.length; i++){
if (firstName === contacts [i].firstName) {
if (contacts[i].hasOwnProperty(prop))
return contacts[i][prop];
return 'No such property';
}
return 'No such contact';
}
}
aday091 sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:warning: aday091 already gave khaduch points
budgetController
is an object with property publicTest
budgetController
is a function
@RobMeador on the second example, when you type the line
budgetController();
it runs the function and return the object but you didn't store that object anywhere
js return arr.shift();
is both removing the last item in the array and returning its value?
return arr.shift();
var budgetController = function() {
var x = 23;
var add = function(a) {
return x + a;
}
return {
publicTest: function(b) {
console.log(add(b));
}
}
};
var newVar = budgetController(); // After this line, shouldn't var budgetController have access to publicTest?
newVar.publicTest(5);
robmeador sends brownie points to @longnt80 :sparkles: :thumbsup: :sparkles:
:cookie: 386 | @longnt80 |http://www.freecodecamp.com/longnt80
aday091 sends brownie points to @khaduch :sparkles: :thumbsup: :sparkles:
:warning: aday091 already gave khaduch points
budgetController().publicTest(5);
//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++){
var boolean= contacts[i].hasOwnProperty(firstName);
if(boolean === true){
var val1="";
val1=contacts[i].firstName;
return val1;
}
else{
return "No such contact";
}
for(var j=0; j<contacts[i].length; j++){
while(boolean === true){
var boolean2= contacts[i].hasOwnProperty(prop);
if(boolean2 === true){
var val2="";
val2 += contacts[i][j].prop;
return val2;
}
else{
return "No such property";
}
}
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
//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++){
var boolean= contacts[i].hasOwnProperty(firstName);
if(boolean === true){
var val1="";
val1=contacts[i].firstName;
return val1;
}
else{
return "No such contact";
}
for(var j=0; j<contacts[i].length; j++){
while(boolean === true){
var boolean2= contacts[i].hasOwnProperty(prop);
if(boolean2 === true){
var val2="";
val2 += contacts[i][j].prop;
return val2;
}
else{
return "No such property";
}
}
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
Wow, your function is pretty complex. There seem to be a few misunderstandings.firstName
contains a string to compare to the value of contacts[i].firstName
. It does not contain a property name, and contacts[i].firstName
is probably nothing to return.
You should return "No such contact" after you've made sure none of the objects' firstName property matches the string in firstName
.
contacts[i]
has no length property. Also, don't use .prop
, which is equal to ["prop"]
and uses static property name "prop" when you meant to use the string in variable prop
, which would require [prop]
firstName
to contacts[i].firstName
. Neither of them is a value to return, just that a match between the two means you've found the contact.
return startIndex == target ? true : false;
firstName
property in this case.
? true : false
does not change the meaning
return startIndex == target;
if (contacts[i].firstName === firstName) {
and inside that have an if-else or the ternary operator, testing the existence of the property named by prop
:star2: 4405 | @blauelf |http://www.freecodecamp.com/blauelf
martin-alvarado-a sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
function steamrollArray(arr) {
arr = arr.slice(); // creating copy as I'm going to mutate
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
var newArr = arr.splice(i, 1)[0];
Array.prototype.splice.apply(arr, [i, 0].concat(newArr));
i--;
}
}
return arr;
}
function steamrollArray(arr) {
while (arr.some(Array.isArray)) {
arr = Array.prototype.concat.apply([],arr);
}
return arr;
}
waingor sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 4406 | @blauelf |http://www.freecodecamp.com/blauelf
@Blauelf @Masd925 I'm having a problem implementing Dijkstra's algorithm. I need to keep track of the path, so the idea was to create an array of objects as nodes. However when I do this, I don't get the output I expected (an array filled with similar objects):
let nodes = new Array(numberOfIntersections).fill({cost: Infinity, path:[], visited: false});
all objects share the same reference, so when I change one, I change them all.
I also tried:
let nodes = new Array(numberOfIntersections).map(()=>({cost: Infinity, path:[], visited: false}));
but this resulted in an empty array (of the right length).
...
I'm confused.