Even numbers in an array (7kyu): Codewars (TDD in JavaScript)

Mar 13, 2020 13:01 · 442 words · 3 minute read github new array try current

Hi! It’s Friday. So let’s chill and do something easy today. If this is your first time here and you want to learn Frontend and JavaScript, start right now by subscribing, and don’t forget to turn on the subtitles. [Music playing] Let’s solve today kata titled “Even numbers in an array.” Given an array of digital numbers, return a new array of length number containing the last even numbers from the original array (in the same order). Okay. The original array will be not empty and will contain at least “number” even numbers. Okay, let’s try. So.

00:46 - I have “evenNumbers” and for this array last three elements should be [4, 6, 8]. Okay. Let’s start from the plane solution. Let’s create an array that should contain only result numbers and then loop over all elements in this array starting from 0 and till the end of the “array.length.” Then “i++” And if the current element “i” modulo 2 equals 0 (so it’s even) then result push this element. And then return result splice it for last element, so it’s “result.length” minus “number,” up to “number.” Let’s try. Yes, so that’s correct. Let’s optimize this solution. Let’s use a map method. We have a result array then instead of this “for loop” I need map over elements of this array.

02:01 - So for the current element (let’s call it “x”), if “x” modulo 2 equals 0 then result push this current element. That’s all. And then return splice and… By the way. This “length number” and “number” we can replace using just “-number” because this equals to the original equation. We take only last “n” numbers. And let’s try. Oh, sure! I need to wrap this “if” using curly brackets. Let’s try again. Good. I like it. Now we can refactor this solution using only filter methods and simply return that in one string. Okay, let’s replace it. I don’t need this and don’t need this. And I return “array filter” for elements that have a reminder equals 0 and then simply slice them. Let’s do that in one line. Like that. Let’s try. Yes, so that’s correct.

03:26 - And now we can refactor this solution using an arrow function so for that I return like this. Let’s try. Over all test cases. Yes it works. I like it. My code is available on GitHub. Documentation is available in the Internet. Follow the links if you’re eager to get more. If you like this video give it “thumbs up”, share it with your friends, subscribe to the channel and watch other episodes. Thanks for watching and dive deeper. .