0

i have a problem with the code, idk how to optimalize the code to work for every new "person" in object.

customers_data={
    'Ben10': [22, 30, 11, 17, 15, 52, 27, 12],
    'Sameer': [5, 17, 30, 33, 40, 22, 26, 10, 11, 45],
    'Zeeshan': [22, 30, 11, 5, 17, 30, 6, 57] 
    }
var count = 0
for (let e of customers_data.Ben10) { if (e >= 20) count ++}
    if (count >= 5) {console.log("Ben10 has Premium Membership")}
    count = 0
for (let e of customers_data.Sameer) { if (e >= 20) count ++}
    if (count >= 5) {console.log("Sameer has Premium Membership")}
    count = 0
for (let e of customers_data.Zeeshan) { if (e >= 20) count ++}
    if (count >= 5) {console.log("Zeeshan has Premium Membership"); count = 0}
    count = 0
radek155
  • 11
  • 1

3 Answers3

1

customers_data={
    'Ben10': [22, 30, 11, 17, 15, 52, 27, 12],
    'Sameer': [5, 17, 30, 33, 40, 22, 26, 10, 11, 45],
    'Zeeshan': [22, 30, 11, 5, 17, 30, 6, 57] 
    }
var count = 0
for(let prop in customers_data)
{
  for (let e of customers_data[prop]) { if (e >= 20) count ++}
      if (count >= 5) {console.log(prop + " has Premium Membership")}
      count = 0
}
YuTing
  • 6,555
  • 2
  • 6
  • 16
0

Use two loops. Outer to loop name => values, inner to loop values

let customers_data = {
    'Ben10': [22, 30, 11, 17, 15, 52, 27, 12],
    'Sameer': [5, 17, 30, 33, 40, 22, 26, 10, 11, 45],
    'Zeeshan': [22, 30, 11, 5, 17, 30, 6, 57] 
    }

for (let dataKey in customers_data) {
    let count = 0;

    for (let value of customers_data[dataKey]) {
        if (value >= 20) {
            count++;
        }
    }
    
    if (count >= 5) {
        console.log(dataKey + " has Premium Membership");
    }
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

You can DRY this out a little by using a function into which you pass the data, and the name you want to check, and then return a message based on the result.

const customers_data = {
  Ben10: [22, 30, 11, 17, 15, 52, 27, 12],
  Sameer: [5, 17, 30, 33, 40, 22, 26, 10, 11, 45],
  Zeeshan: [22, 30, 11, 5, 17, 30, 6, 57]
}

// Accept data and a name
function hasMembership(data, name) {

  // `filter` out the numbers that are greater
  //  or equal to 20
  const greaterThan20 = data[name].filter(entry => {
    return entry >= 20;
  });

  // If the length of the filtered array is
  // greater or equal to five, return a positive message
  if (greaterThan20.length >= 5) {
    return `${name} has Premium Membership!`;
  }

  // Otherwise return something else
  return `Boo. No membership for ${name}.`;

}

console.log(hasMembership(customers_data, 'Ben10'));
console.log(hasMembership(customers_data, 'Sameer'));
console.log(hasMembership(customers_data, 'Zeeshan'));

Additional documentation

Andy
  • 61,948
  • 13
  • 68
  • 95