Search code examples
javascriptarraysobjectpropertiesfor-in-loop

Compare Object Property Keys with Object Property Values in Array, Return "Total Points"


Link to Codewars kata. Basically, as far as I understand:

  • If the property key (x) is greater than the property value (y), add 3 points to points.

  • If the property key(x) is less than the property value (y), add 0 points to points.

  • If the property key (x) is equal to the property value (y), add 1 point to points.

I need to iterate through each individual property to compare the x value against the y value. But what I'm trying isn't working:

function points(games) {

  let points = 0;

  for (let key in games) {
    let item = games[key];
    let x = item[0];
    let y = item[1];
    //compare x values against y values in items
    if (x > y) {
      points += 3;
    }
    if (x < y) {
      points += 0;
    }
    if (x === y) {
      points += 1;
    }
  }
  return points;
}

console.log(points(["1:0", "2:0", "3:0", "4:0", "2:1", "3:1", "4:1", "3:2", "4:2", "4:3"]));

This is returning 0.

How can I iterate through each property in the array to do the comparison in each individual property?

EDIT - After splitting strings into arrays for comparison, I am still not grasping how to compare x values in the arrays agains the y values:

function points(games) {
  let points = 0;

  for (let i = 0; i < games.length; i++) {
    let properties = games[i].split();

    if (properties[0] > properties[1]) {
      points += 3;
    }
    if (properties[0] < properties[1]) {
      points += 0;
    }
    if (properties[0] === properties[1]) {
      points += 1;
    }
  }
  return points;
}

Solution

  • Read about reduce and map for further information

    function points(games) {
    
      return games.map(game => {
        let points = 0;
        let item = game.split(':');
        let x = item[0];
        let y = item[1];
        //compare x values against y values in items
        if (x > y) {
          points += 3;
        }
        if (x < y) {
          points += 0;
        }
        if (x === y) {
          points += 1;
        }
        return points;
      }).reduce((sum, curr) => (sum += curr),0);
    }
    
    console.log(points(["1:0", "2:0", "3:0", "4:0", "2:1", "3:1", "4:1", "3:2", "4:2", "4:3"]));