skip to Main Content

I am working on a class assignment where I need to make write a Loop. I made an array of objects for houses. I created a For Loop to sort the array by the price of the houses. The array displays in the console of the webpage but not in the actual webpage. Below are the extracts of what the console shows, what the webpage shows, and my code.

console log

  1. (4) [{…}, {…}, {…}, {…}]

    1. 0: {id: ‘house4’, stories: 1, squareFoot: 1130, color: ‘white’, year: 1961, …}

    2. 1: {id: ‘house1’, stories: 1, squareFoot: 1285, color: ‘beige’, year: 2018, …}

    3. 2: {id: ‘house2’, stories: 1, squareFoot: 1560, color: ‘brown’, year: 1983, …}

    4. 3: {id: ‘house3’, stories: 2, squareFoot: 2975, color: ‘tan’, year: 2008, …}

    5. length: 4

    6. [[Prototype]]: Array(0)

webpage

[object Object],[object Object],[object Object],[object Object]

I have watched several videos about sorting arrays, but they all only display to the console log. I tried to modify my code to be similar to the example used in my lecture video as well, but still no output.

let houses = [
  {id:"house1", stories:1, squareFoot:1285, color:"beige", year:2018, bedrooms:3, bathrooms:2, price:285000},
  {id:"house2", stories:1, squareFoot:1560, color:"brown", year:1983, bedrooms:3, bathrooms:3, price:345000}, 
  {id:"house3", stories:2, squareFoot:2975, color:"tan", year:2008, bedrooms:4, bathrooms:3, price:415000}, 
  {id:"house4", stories:1, squareFoot:1130, color:"white", year:1961, bedrooms:2, bathrooms:2, price:215000}];
for (i=0; i<1; i++) {
  houses.sort((a, b) => a.price - b.price);
  document.getElementById("houses").innerHTML=houses;
}
console.log(houses);
<p id="houses"></p>

2

Answers


  1. Several things worth noting.

    The for loop

    Notice that your two statements inside the for loop do not depend on the index i:

    houses.sort((a, b) => a.price - b.price);
    document.getElementById("houses").innerHTML=houses;
    

    That means that you’re just repeating the same operation each time you loop. So no need for the loop! The sort method sorts the array in one line.

    However, if your assignment was to use a for loop, I’m guessing that you cannot use the built-in sort method, and that the point is for you to write your own sorting function.

    That is up to you; just note that, as it is, the following for:

    for (i=0; i<1; i++)
    

    only loops once. From here on know that you will have to replace the line

    houses.sort((a, b) => a.price - b.price);
    

    with your own sorting function.

    The HTML output

    You have already seen that setting the text of your HTML paragraph as houses doesn’t display the contents of the array. That is because it is – surprise – an array1. HTML deals with text, so to achieve your goal, you first need to convert houses into text.

    There are several ways to do this, but best practice would probably be to use the JSON.stringify method, that outputs the representation of an object as a string. You can see its effect in the following snippet:

    let houses = [{id:"house1", stories:1, squareFoot:1285, color:"beige", year:2018, bedrooms:3, bathrooms:2, price:285000},
                    {id:"house2", stories:1, squareFoot:1560, color:"brown", year:1983, bedrooms:3, bathrooms:3, price:345000}, 
                    {id:"house3", stories:2, squareFoot:2975, color:"tan", year:2008, bedrooms:4, bathrooms:3, price:415000}, 
                    {id:"house4", stories:1, squareFoot:1130, color:"white", year:1961, bedrooms:2, bathrooms:2, price:215000}];
    
    houses.sort((a, b) => a.price - b.price);
    document.getElementById("houses").innerHTML = JSON.stringify(houses);
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
      </head>
      <body>
        <p id ="houses"></p>
      </body>
    </html>

    Addendum

    In this case, it is probably better to write:

    document.getElementById("houses").textContent = JSON.stringify(houses);
    

    ; rather than:

    document.getElementById("houses").innerHTML = JSON.stringify(houses);
    

    References

    JSON.stringify()


    1Any other object would behave in the same way.

    Login or Signup to reply.
  2. innerHTML converts the object to a string. The string representation of an object is [object Object] – as you noticed already. You can use JSON.stringify to display the contents of every object, or extract the values from it (looping through Object.keys/Object.values). Here is a snippet doing that.

    const housesBox = document.querySelector(`#houses`);
    let houses = [
      {id:"house1", stories:1, squareFoot:1285, color:"beige", year:2018, bedrooms:3, bathrooms:2, price:285000},
      {id:"house2", stories:1, squareFoot:1560, color:"brown", year:1983, bedrooms:3, bathrooms:3, price:345000}, 
      {id:"house3", stories:2, squareFoot:2975, color:"tan", year:2008, bedrooms:4, bathrooms:3, price:415000}, 
      {id:"house4", stories:1, squareFoot:1130, color:"white", year:1961, bedrooms:2, bathrooms:2, price:215000}]
    .sort( (a,b) => a.price - b.price);
    const labels = Object.keys(houses[0]);
    
    // create a header
    labels.forEach((key, i) => 
      housesBox.append(`${key}${i < labels.length-1 ? `;` : ``}`));
    housesBox.append(document.createElement(`br`), `-`.repeat(75));
    
    // add the values
    houses.forEach((house, i) => {
      const values = Object.values(house);
      housesBox.append(document.createElement(`br`));
      values.forEach( (value, i) => 
        housesBox.append(`${value}${i < values.length - 1 ? `;` : ``}`));
    });
    <p id="houses"></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search