Best way to refactor code?

I have some data that looks like this:

[
{survey: "2016-07-01", village: "1", adjmatrix_key: "1", HHnum_in_village: "1", hhid: .....
{survey: "2016-07-01", village: "1", adjmatrix_key: "1", HHnum_in_village: "2", hhid: .....
.
.
]

I want to go through each element of array and count up:

  1. The number of households that rent, lease, etc
  2. The number of households that have elec vs don’t
  3. The number of households that are hindu, muslim, or christian
  4. The number of households that have a latrine vs don’t

Right now, I have only written the code for (1) and it looks like this:

countAllVariables(inputData) {
    let homeOwnership = [];
    let homeReligion = [];
    let homeElec = [];
    let homeLat = [];
const countRent = inputData.filter(each => each.ownrent === "RENTED")
  .length;

const countLease = inputData.filter(each => each.ownrent === "LEASED")
  .length;

const countGmentOwn = inputData.filter(
  each => each.ownrent === "GIVEN BY GOVERNMENT"
).length;

const countNAHome = inputData.filter(each => each.ownrent === "NA").length;

homeOwnership.push(
  { x: "LEASED", y: countLease },
  { x: "RENTED", y: countRent },
  { x: "GIVEN BY GOVERNMENT", y: countGmentOwn },
  { x: "NA", y: countNAHome }
);

return homeOwnership;

}

I feel like there has to be a better way to than to repeat the same logic again and again for the remaining variables, i.e. Religion, Electricity, Latrine.

If anyone has ideas, please let me know - thanks!

It seems this information would be better suited in an object like:

{
  "LEASED": countGoesHere,
  "RENTED": countGoesHere,
  "GIVEN BY GOVERNMENT": countGoesHere,
  "NA": countGoesHere
}

If the above would work, then you could just initialize the object like:

const homeOwnership = {
  "LEASED": 0,
  "RENTED": 0,
  "GIVEN BY GOVERNMENT": 0,
  "NA": 0
};

and then update the object while iterating through the array:

for (let { ownrent } of inputData) {
  if (homeOwnership.hasOwnProperty(ownrent) {
    homeOwnership[ownrent]++;
  }
}

I know this is not exactly what you asked for, but it could help guide you to a solution. Ideally, you would only iterate through inputData one time.

1 Like