1

I'm building a property valuation form.
U can filter by postcode and type.
after filtering, I should show a list with the properties and the average price but I don't know why the sum is not working.

Thank you in advance for your help :)
here my code ................................. ... ... ... ... ... ... ... ...

var houses = [{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "101"
},
{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "200"
},
{
    Postcode: "2010",
    Type: "typehouse1",
    Price: "234"
},
{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "100"
},
{
    Postcode: "2012",
    Type: "typehouse2",
    Price: "500"
},
{
    Postcode: "2011",
    Type: "typehouse2",
    Price: "100"
},
{
    Postcode: "2013",
    Type: "typehouse2",
    Price: "100"
},
{
    Postcode: "2013",
    Type: "typehouse2",
    Price: "455"
}];
var postcodeArray = [];
var typeArray = [];

// adding unique years to yearsArray
$.each(houses, function (index) {
    var postcode = houses[index].Postcode;
    if ($.inArray(postcode, postcodeArray) == -1) {
        postcodeArray.push(postcode);
    }
});
    
//sorting by postcode
postcodeArray.sort();
var $pcode = $("#postcode");
var $housetype = $("#type");
var $container = $("#details").find("tbody");
// append the years to select
$.each(postcodeArray, function (i) {
    $pcode.append('<option value="' + postcodeArray[i] + '">' + postcodeArray[i] + '</option>');
});

$pcode.change(function () {
    var selectedpcode = this.value;
    //filter based on  selected postcode.
    typeArray = jQuery.grep(houses, function (product, i) {
        return product.Postcode == selectedpcode;
    });
    
    updateTable(typeArray);
});

$housetype.change(function () {
    var selectedtype = this.value;
    //filter select based on selected type
    selectedArray = jQuery.grep(typeArray, function (product, i) {
        return product.Type == selectedtype;
        
    });
    updateTable(selectedArray);

    var sum = 0;
      
      $(selectedArray).each(function() {
        sum += $(this)[0].Price;
        console.log("Added: ", $(this)[0].Price) 
      });
      
      console.log("Sum is:", sum);
      console.log("The average is:", sum / selectedArray.length)
});
    
    
      

//To update the table element with selected items
updateTable = function (collection) {
    $container.empty();
    for (var i = 0; i < collection.length; i++) {
        $container.append("<tr><td>" + collection[i].Postcode + "</td><td> " + collection[i].Type + "</td><td>" + collection[i].Price + "</td></tr>");
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="DrpDwn">
        Postoce<input id="postcode"></input>
        House type:<select id="type">
                <option>None</option>
                <option value="typehouse1">type house 1</option>
                <option value="typehouse2">type house 2</option>
            </select>       
</div>
<br />
Filtered houses information
    <table id="details"  border="1" cellpadding="2" cellspacing="2">
    <thead>
        <tr>
            <th>Postcode</th>
            <th>Type</th>
            <th>Price</th>
        </tr>
    </thead> 
    <tbody></tbody>   
</table>

1
  • Can you provide steps of reproducing the problem? I'm not sure how it should work. Commented May 20, 2021 at 20:07

2 Answers 2

0

You could try simplifying your code a bit. I've re-worked the code a bit and think you may find it helpful. I've detailed the steps with comments in the code:

const houses = [{
    Postcode: "2011",
    Type: "typehouse1",
    Price: "101"
  }, {
    Postcode: "2011",
    Type: "typehouse1",
    Price: "200"
  }, {
    Postcode: "2010",
    Type: "typehouse1",
    Price: "234"
  }, {
    Postcode: "2011",
    Type: "typehouse1",
    Price: "100"
  }, {
    Postcode: "2012",
    Type: "typehouse2",
    Price: "500"
  },
  {
    Postcode: "2011",
    Type: "typehouse2",
    Price: "100"
  }, {
    Postcode: "2013",
    Type: "typehouse2",
    Price: "100"
  }, {
    Postcode: "2013",
    Type: "typehouse2",
    Price: "455"
  }
];

// Get references to the elements that we'll be working with
const tbodyEl = document.querySelector('tbody');
const postcodeInputEl = document.querySelector('#postcode');
const houseTypeInputEl = document.querySelector('#type');
const averagePriceEl = document.querySelector('#average');

// Apply the event handlers to the elements that affect the results
postcodeInputEl.addEventListener('change', updateTableWithResults);
houseTypeInputEl.addEventListener('change', updateTableWithResults);

function updateTableWithResults() {
  // Clear the previous result rows and average house costs
  clearExistingResults();

  // Start by getting all the houses in the requested zip code
  let results = getHousesInZip(postcodeInputEl.value);

  // Apply house type filter 
  if (houseTypeInputEl.value !== 'None') {
    results = results.filter(house => house.Type === houseTypeInputEl.value);
  }

  // Generate the HTML and append it to the tbody
  results.map(convertHouseToTrElement)
    .forEach(trElement => {
      tbodyEl.insertAdjacentHTML('beforeend', trElement)
    });

  // Calculate the average and display it
  if (results.length > 0) {
    averagePriceEl.innerHTML = `<p>Average house price = $${getAverageHousePrice(results).toFixed(2)}</p>`;
  }
}

function clearExistingResults() {
  tbodyEl.innerHTML = '';
  averagePriceEl.innerHTML = '';
}

function getHousesInZip(zip) {
  return houses.filter(house => house.Postcode == zip);
}

function convertHouseToTrElement(house) {
  return `<tr><td>${house.Postcode}</td><td>${house.Type}</td><td>${house.Price}</td></tr>`;
}

function getAverageHousePrice(houses) {
  return (houses.reduce((sum, house) => {
    sum += parseInt(house.Price);

    return sum;
  }, 0) / houses.length);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="DrpDwn">
  Postcode<input id="postcode"> House type:
  <select id="type">
    <option>None</option>
    <option value="typehouse1">type house 1</option>
    <option value="typehouse2">type house 2</option>
  </select>
</div>
<br /> Filtered houses information
<table id="details" border="1" cellpadding="2" cellspacing="2">
  <thead>
    <tr>
      <th>Postcode</th>
      <th>Type</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<div id="average"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

Your sum is not working, because JS is summing up strings, which gives You concatenation.

All You need to do is to replace this part:

sum += $(this)[0].Price;

with

sum += parseInt($(this)[0].Price);

Comments