-1

I want to count the wins and losses out of an array of matches but for some reason it doesn't work. In theory it should work but both output 0.

Here is my code I'm using handlebars so the {{ work!

const matches = [{
  id: '9',
  primary_player: 'player1',
  secondary_player: 'player2',
  size: '5',
  result: '0'
}]

const losses = matches.filter(e => e.result == "0" && e.primary_player == "player1").length;

const wins = matches.filter(e => e.result == "1" && e.primary_player == "player1").length;

console.log(losses,wins)
robinnlmn
  • 21
  • 1
  • 9
  • What does your `matches` array look like? – Marco May 07 '22 at 20:46
  • @Marco {id: '9', primary_player: 'player1', secondary_player: 'player2', size: '5', result: '0'} – robinnlmn May 07 '22 at 20:47
  • what is the `"{{user.nickname}}"` supposed to be? At the moment you're matching on that literal string, so looking at your starting array it's no surprise this doesn't return any results. If you're trying to match on a variable then you should use just `user.nickname`, no need for any `{{` (which is not valid syntax in Javascript, but you're including it in a string literal so there's no actual error here, just the wrong result) – Robin Zigmond May 07 '22 at 20:52
  • Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan May 07 '22 at 20:52
  • @RobinZigmond I'm using handlebars and this gives me access to the users name – robinnlmn May 07 '22 at 20:52
  • I made you a snippet – mplungjan May 07 '22 at 20:54
  • 1
    `'0' !== 0` - change the test or the value to compare strings or numbers – mplungjan May 07 '22 at 20:55

1 Answers1

-1

It looks like the problem is just your double quotes wrapped around the primary_player check -- they're not needed in the evaluation. Also, I'm not sure that your length check at the end is useful in any way? Please do correct me, though, if you need it in there (and perhaps explain what you're trying to do with it).

Anyway, this should work (if your matches.result really is a boolean):

const losses = matches.filter(e => e.result === 0 && e.primary_player == user.nickname);

If matches.result is actually a string, which is the more probable data type, then you'll can drop the strict equality check (===):

const losses = matches.filter(e => e.result == 0 && e.primary_player == user.nickname);
Marco
  • 511
  • 6
  • 16