S.H
S.H

Reputation: 703

Comparing numerals within indexed Elements in an array Javascript

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

Upvotes: 2

Views: 36

Answers (1)

Eugene Tsakh
Eugene Tsakh

Reputation: 2879

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
  }
});

Upvotes: 3

Related Questions