This forum is now read-only. Please use our new forums at discuss.codecademy.com.

1124 points
909a0cc4c5321f5e4a2151a3cca53402?s=140&d=retro
Submitted by
pbbrennan
over 4 years ago

8/8 - Formatting the output & returning all keys' values.

Having trouble figuring out how to return all of the contact information formatted nicely in this exercise. I thought I could use the same function with a for/in loop, then just return the key's value, like this:

var format = function(name) {
for(var x in friends) {
if(friends[x].firstName === name) {
return ("First Name: " + friends[x].firstName);
return ("Last Name: " + friends[x].lastName);
}
}
};
format("Bill");

Anyone know why this doesn't work - or how to get it to format the way it says in the exercise?


23 votes

permalink

We have a search function that finds a match, or not. We can then hand that result to the format function, and not have to perform another query. We have the data, now it just needs to be formatted for output. So there will be no if (x===name).

It's also important to note that anything after a return is unreachable, so we would never write,

return ...
return ... (or any code)

The second line is not reachable after return.

The search function at present both logs and returns the matched object. For our purposes we can comment out or remove the console.log() statement and just keep the return statement.

In the end, what we hope to be able to do is pass the search function return value to the format function:

format(search("Bill"));

At present, if no match is found in search() the return value is undefined which can be made to suit our purposes. The format function can check for this.

function format(obj){
    if (obj){
        // go ahead with format and output
    } else {
        console.log("\nThe name was not found.");
    }
}

Given this scaffold to work within, see how you make out now with formatting the single object that is passed to the format() function. Remember, we know the structure of the data in the returned object, so we can refer to it directly, without need of a loop.

var formatStr = "";
formatStr += "\nName:    "+obj.firstName+" "+obj.lastName;
formatStr += "\nNumber:  "+obj.number;
formatStr += "\nAddress: "+obj.address.join(, );
console.log(formatStr);

Putting it all together, we have,

var search = function(name) {
    for(var key in friends) {
        if(friends[key].firstName === name) {
            return friends[key];
        }
    }
};
var format = function(obj){
    if (obj){
        var str = "";
        str += "\nName:    "+obj.firstName+" "+obj.lastName;
        str += "\nNumber:  "+obj.number;
        str += "\nAddress: "+obj.address.join(', ');
        console.log(str);
    } else {
        console.log("\nThe name was not found.");
    }
};

format(search("Bill"));
format(search("Steve"));
format(search("Joe"));
//
Name:    Bill Gates
Number:  (206) 555-5555
Address: One Microsoft Way, Redmond, WA, 98052

Name:    Steve Jobs
Number:  (408) 996-1010
Address: 10260 Bandley Dr., Cupertino, CA, 95014

The name was not found.

8995 points
5958b8ebe12813a2a3000034_980106998
Submitted by
Roy
over 4 years ago

9 Comments

5811f15658212277b30001f0_107138836 Florence Okosun over 4 years ago

var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
}
};

var list = function(friends){
for (var firstName in friends){
var result = firstName;
console.log(result);
}

}

var search = function(name) {
for(var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[firstName]);
return friends[firstName];
}
}
}

4f692428a5e07cb5b114ad12995cf41e?s=140&d=retro Susannah Skyer Gupta about 4 years ago

Roy, I am definitely going to need to take the time to go back and think more about this later, since right now I am pretty much just copying and pasting, but I wanted to say: thank you! I really appreciate you taking the time to explain how to extend this to produce attractively formatted output!

B192a279cc81cd246abb5d46e5e10845?s=140&d=retro ddvorak87 about 4 years ago

I don't quite get your code. Whhy do you declare the variable str and then why do you use the += on it several times?

5958b8ebe12813a2a3000034_980106998 Roy about 4 years ago

The variable begins as an empty string with each iteration. We build up the string with first an assignment, then with successive concatenations (+=). Once the string is built, we log it. The output is multi-line and relies upon the \n newline escape sequence rather than logging three (or later) four separate lines. console.log() is very slow, so everything we can do before hand helps to reduce the number of calls we make to the function. Not only that, by only logging once, the code can be edited quickly if I ever want to run it in a web browser (innerHTML, or textContent, for instance).

63e6d8f5e176bc2ac5cb75b3b4bf4d17?s=140&d=retro Rithvik Chatterjee about 4 years ago

can you please explain the format thingy?

5958b8ebe12813a2a3000034_980106998 Roy about 4 years ago

Its a custom function, not built into JavaScript, and it is fairly self-explanatory. Perhaps a review of JavaScript functions and objects is in order?

63e6d8f5e176bc2ac5cb75b3b4bf4d17?s=140&d=retro Rithvik Chatterjee about 4 years ago

oh ya, stupid me. Can you please explain the -
1) += stuff, i don't get what they do.
2) Clarifying, "\n" automatically logs the text one line below, without the need of console.logs seperately. But if so, why is it that for the first part(Bill's name) it doesn't skip a line.
3) PLease, please explain the \n syntax
4) What exactly were you joining in the address, plus can you please explain the ( ' , ')(syntax, use)
5) Can i umm first search and then format rather than the opposite, how and why does it affect the code?

Thanks in advance

5958b8ebe12813a2a3000034_980106998 Roy about 4 years ago

Search: Array.prototype.join(). Search: JavaScript escape sequence. Search: JavaScript arithmetic operators and string concatenation.

35656d7db99f984114114979a9b9a2ac?s=140&d=retro Tyler Taylor about 4 years ago

It's still magic to me how you came up with this solution, but for that reason I am bookmarking this and will revisit it later and hopefully have a better grasp of it. This challenge made me feel stupid!


7 votes

permalink

Some quick clarification before it becomes confusing:

\n

This is known as an escape sequence that tells console.log() to insert a newline character. This is what gives each entry its own line on the display.

if (obj)

In a conditional, a plain object, {} will cast to a Boolean true. This is what is known as a true value, even though it is actually not a value. The main thing is that if obj is not an object, then it is undefined, so false, as in a false value.

if (obj.length)

A plain object does not have a length property. Only strings and arrays do. Since a not found return value will be a string, it passes. An object does not.

array.join(', ')

As we can see, the join() method is a property of the Array object that converts an array to a string. The argument, (', ') supplies the separator, in this case, comma space.

8995 points
5958b8ebe12813a2a3000034_980106998
Submitted by
Roy
over 4 years ago

1 Comment

Picture Victoria Kariolic over 4 years ago

So, in the address array, how could we get it to display as the example shows --> line1: Address Part 1 / line2: City, State, Code

My solution attempt was like this formatStr += "\nAddress: " + obj.address[0] +"\n\t" + obj.address[1] + ", " + obj.address[2] + " " + obj.address[3];
Could there be a more compact way to do something like this?


5 votes

permalink

Here's a variation that returns the name if not found (as opposed to undefined) ...

var search = function(name) {
    for(var key in friends) {
        if(friends[key].firstName === name) {
            return friends[key];
        }
    }
    return name;
};
var format = function(obj){
    var str = "";
    if (obj.length){
        str = "\nThe name, "+obj+", was not found.";
    } else {
        str += "\nName:    "+obj.firstName+" "+obj.lastName;
        str += "\nNumber:  "+obj.number;
        str += "\nAddress: "+obj.address.join(', ');
    }
    console.log(str);
};

format(search("Bill"));
format(search("Steve"));
format(search("Joe"));
//
Name:    Bill Gates
Number:  (206) 555-5555
Address: One Microsoft Way, Redmond, WA, 98052

Name:    Steve Jobs
Number:  (408) 996-1010
Address: 10260 Bandley Dr., Cupertino, CA, 95014

The name, Joe, was not found.

8995 points
5958b8ebe12813a2a3000034_980106998
Submitted by
Roy
over 4 years ago

9 Comments

55a183d19113cb0e4200069f_989288560 Vipul Jurel over 4 years ago

sir you say "if(obj.length)" A plain object does not have a length property. i am not properly understand this statement.Tell me how when pass function name
"format(search("Bill"));" then how "if(obj.length)" know this "search("Bill")" are valid ?

5958b8ebe12813a2a3000034_980106998 Roy over 4 years ago

As you observe, objects do not have a length, or rather their length property value is always 0. if (obj.length) then it must be a string. This was just a simple way of separating string from object.

5958b8ebe12813a2a3000034_980106998 Roy over 4 years ago

If no match is found, the name is returned, a string. if a match is found, the object is returned.

55a183d19113cb0e4200069f_989288560 Vipul Jurel over 4 years ago

thanks sir

C8f5f0b3884522d6c7032738481e583e?s=140&d=retro courage jahmon over 4 years ago

You are going too far with this we are newbies so try explaining in simple language.I bet you the one who said "thanks sir" just copied and pasted

5958b8ebe12813a2a3000034_980106998 Roy over 4 years ago

It won't matter. This is not lesson code, purely demonstration. We don't need any code in the last lesson. It's a freebie with no SCT. All that is suggested is that we find ways to improve upon what we built in the module. We have to stretch the canvas a little wider if we're to explore and build upon what is learned.

Ce8f3f1f9e81e3edd426b7596c8a6dea?s=140&d=retro dnorthrupvagmail.com about 4 years ago

No, 'courage jahmon', I loved Roy's explanation - He gave a simple break-down, and it's only confusing because he introduce /n and format which hasn't been taught. But by this point in the course, you should be able to reverse-engineer what he posted to get a good foundation.

5958b8ebe12813a2a3000034_980106998 Roy about 4 years ago

\n is the 'newline' escape sequence. format is created right in the code and is pretty self-explanatory. As one may surmise, I'm not a big fan of console.log so prepare one long output string and log it all at the end, that is why I have \n in the code, so it prints to multiple lines with only one console.log().

12e35a73502a4623bc1b9d4d19b3bc27?s=140&d=retro Olga Tegay about 4 years ago

Thanks a lot, Roy!


1 vote

permalink

@Victoria,

Using the variation above with "The name, Joe, was not found", change this,

    str += "\nAddress: "+obj.address.join(', ');

to this,

    str += "\nAddress: "+obj.address[0]+",";
    str += "\n         "+obj.address.slice(1).join(', ');

Output

Name:    Bill Gates
Number:  (206) 555-5555
Address: One Microsoft Way,
         Redmond, WA, 98052

Name:    Steve Jobs
Number:  (408) 555-5555
Address: 1 Infinite Loop,
         Cupertino, CA, 95014

The name, Joe, was not found.

8995 points
5958b8ebe12813a2a3000034_980106998
Submitted by
Roy
over 4 years ago

6 Comments

67c2e36071a91cb3e20824e2ade4c05b?s=140&d=retro ltraub over 4 years ago

Hi Roy,
What does adding the slice() method do? Thanks!

5958b8ebe12813a2a3000034_980106998 Roy over 4 years ago

The slice method makes a shallow copy of the array beginning at the index specified, or 0 if no parameter is supplied. It's how we can copy an array, or a subset of elements within the array for processing on the side. The original array remains untouched. In the above, if we join() the address array it becomes a string. We don't want that. But a copy? Sure, go for it.

Picture Hoa Hoang about 4 years ago

str += "\nAddress: "+obj.address.join(', '); hey Roy what does the str+= do?

5958b8ebe12813a2a3000034_980106998 Roy about 4 years ago

We start with str = "something" then we continue to grow the string with str += "something else" and so on. It basically means 'continue to concatenate to the string'.

Picture Hoa Hoang about 4 years ago

yes,and what will happen if you remove them?

5958b8ebe12813a2a3000034_980106998 Roy about 4 years ago

Try it yourself and see. Meanwhile, search "JavaScript arithmetic operators".