Filter Your Content With Javascript

I have been working with Javascript a lot lately and am finding it very much different to C#. Whilst there are many, many differences; there are also a number of similarities too.

I had been working on a cricket scoring system whereby individual balls are entered into the application with a number of meta descriptive data attributes. For example, each ball that is bowled has:

  • a Value (could be 0 – 6)
  • a DeliveryType (score, sundry, dismissal)
  • CurrentOver (when did the delivery occur in the game)
  • Bowler (who bowled)
  • Batsman (who was the facing batsman, and will receive the value added to their score)

Each delivery is added to a LocalStorage JSON array.

A game of cricket can go for 5 days. There can be 90 overs bowled each day, with 6 deliveries per over. This works out to nearly 3000 deliveries each game.  So we end up with data looking like this

delivery: [{"Value":"1","Type":"1","Event":"score","Bowler":"qwdqwe qqwq","Batsman":"eqe qweqweqeqe","Over":"1","BattingTeam":"home"},
{"Value":"2","Type":"2","Event":"score","Bowler":"qwdqwe qqwq","Batsman":"qweqwe qwe qqe","Over":"1","BattingTeam":"home"},
{"Value":"3","Type":"3","Event":"score","Bowler":"qwdqwe qqwq","Batsman":"qweqwe qwe qqe","Over":"1","BattingTeam":"home"},
{"Value":"4","Type":"4","Event":"score","Bowler":"qwdqwe qqwq","Batsman":"eqe qweqweqeqe","Over":"1","BattingTeam":"home"},
{"Value":"5","Type":"5","Event":"score","Bowler":"qwdqwe qqwq","Batsman":"eqe qweqweqeqe","Over":"1","BattingTeam":"home"},
{"Value":"0","Type":".","Event":"score","Bowler":"assdfs sgdfgdg","Batsman":"qweqwe qwe qqe","Over":"1","BattingTeam":"home"}]

It’s easy to work with small numbers like this, but what happens when we get towards the end of the match and we have thousands of values in our dataset? How we we display the deliveries so far in the current over?

I decided to use the Jquery filter method.

// get the localstorage value for the current over
var currentOver = localStorage.getItem("CurrentOver");

// get the array of all deliveries so far in the match
var deliveries = JSON.parse(localStorage.getItem("delivery"));

//  filter the array
var thisOver = $(deliveries).filter(function (i, n) { return n.Over === currentOver });
//  display the over and the balls so far in this over = 34.3
$(".CurrentOver").html(over + '.' + thisOver.length);

It is as easy as that. I use the Over property of the array and return those array items which match the value of currentOver.

For those you interested, you can see the scoring application I wrote here – http://scoring.woolston.com.au.

Til next time …


1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *