dannymac dannymac - 1 year ago 58
Javascript Question

How should I go about making the names bold in this multidimensional array?

What would be the best approach, keeping similar structure, to bold the names only in this array? I can get it working on the entire array (which I have here), but I'm just trying to get the names. I have an idea of an ugly approach to this, but would appreciate some help on something concise and clean looking. Also, I know isn't the best thing to use and I should wrap the array in an object etc, but that's not what I need here. This ties into a bigger problem I'm thinking about and is practice for something larger in the future. Thanks.

var people = [
[ "Daniel",30,"San Francisco",["175 lb"," 6\'0\""] ],
[ "Deryl",29,"Seattle",["165 lb"," 5\'9\""] ],
[ "Mandie",29,"Seattle",["155 lb"," 5\'8\""] ],
[ "Elena",28,"Seattle",["145 lb"," 5\'6\""] ]

for(var i = 0; i < people.length; i++) {
for(var j = 0; j < people.length; j++) {

Answer Source

Change your loop to this...

for(var i = 0; i < people.length; i++) {
    for(var j = 0; j < people[i].length; j++) {
        var text = people[i][j];
        if (j == 0) {
            text = "<b>" + text + "</b>";
        document.write(text + "<br/>");

It does the same as what you previously had, but it wraps the first element in each row with <b> tags. There are better ways to do this, like using css and classes to identify the columns, and in the long run that will make it easier to maintain and modify, but for the sake of learning and fixing this one issue, this will suffice.

Also, there was an issue with the inner loop getting the length of people, rather than the specific row. I fixed that by changing it to people[i].length.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download