Array map and sort in JavaScript. Codingame: Horse Racing Duals – Solved
Articles Blog

Array map and sort in JavaScript. Codingame: Horse Racing Duals – Solved

August 31, 2019


Programming shouldn’t be boring. Let’s solve a Codingame’s puzzle today. [Music playing] Hi! Let’s play and solve a puzzle titled “Horse
Racing Duals” by Codingame. I’m Anatol and you are watching the Good Parts
of the FrontEnd development. [Music playing] The story tells: Casablanca’s hippodrome
is organizing a new type of horse racing: duals. During a dual, only two horses will participate
in the race. This puzzle teaches you Sorting and working
with Arrays and Lists To win at this game it is necessary to try
to select two horses with similar strength. So I need to identify the two closest strengths
and show their difference with an integer. I declare an array using a “new” statement
and set a length of an array. I’m using a “sort” method to sort the array. Put you attention, you need to use an additional
function to sort numbers correctly. Otherwise, number 10 follows number 1, but
not number 2 Also, I’m using a “map” method to create
a new array. This method executes a function with following
parameters: current element, an index and an initial array. Both of these methods return an array, therefore
I can “chain” them. In addition, I’m using an unary operator “+”. This is a shorthand for a “parseInt” operator. Let’s dive into the code. [Music playing] Let’s print the result just in one chain
Create a new Array and read its length Add elements to the array. It’s necessary to enable “map” method usage
and read an initial array Sort this array using the digits’ comparing
function to get a correct order Create a new array by comparing the absolute
difference to the closest element Sort it and print the very first element,
because it possesses a minimal value (difference) Run it and check that all tests are green That’s pretty easy, isn’t it? Next time let’s have a look at The Descent
and talk about loops. [Music playing] My code is available on GitHub
Documentation is available in the Internet Follow the links if you’re eager to get
more. [Music playing] If you like this video give it “thumbs up”,
share it with your friends, subscribe to the channel and watch other episodes. [Music playing] This is all for this week. Thanks for watching and dive deeper.

Only registered users can comment.

  1. Well done! I really like the way you nest functions in single expression, code is clean and easy to read. I am glad that I found your video – I need to learn this style!

Leave a Reply

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