2

given an array like ['8:2', '3:2', …] I want to compare each number within every element of the array. So Index[0] would compare 8 with 3 and so on. If A is equal than B it should get a certain value, if A is less than B it should get another Value. I just don't know how I get these numbers within an indexed element to be compared, so that the new values could be stored into a second array.

I tried this :

function check(games) {
var newArr = [];
var value;
//var newArr = [];
  for (var j=0; j<=games.length; j++){
    if (games[j].a === games[j].b ) {
      value = 0;
      newArr.push(value);
      //alert(newArr);
      //return value;
    }
    else if(games[j].a > games[j].b ) {
      value = 2;
      newArr.push(value);
      //alert(newArr);
    }
    alert(newArr.join(''));
  }

}

check(['3:3', '2:1']);

Than I tried it with for… in But it does not work either… (My code example is shortened)

function check(games) {
var arr = games;
var arrNew = [];
  for (var prop in games) {
    if (a === b) {
    var value = 0;
    arrNew.push(value);
    alert(arrNew.join(''));
    }
  }
}

 check(['3:3', '2:1']);

How can I compare elements which are stored within on index? Like Index[0] = ("3:3') - How do I compare a with b so that I can iterate to the next Index?

Thank you

1 Answer 1

3
const list = ['8:2', '3:2'];
list.forEach((e) => {
  const [a, b] = e.split(':').map(Number);
  if (a > b) {
    // a is greater than b
  } else if (a < b) {
    // b is greater than a
  } else {
    // a and b are equal
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

@OriDrori you're right, thank you for pointing, updated the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.