Day 23 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/which-are-in

Time: 15 minutes

What I’ve learnt: Another string iterator. This time with two arrays of words, and I had to return the words that were found inside the words from the second array. Somewhat similar to yesterday’s.

I mapped through the second array which contained the bigger set of words, and inside that map ran a filter to check which if the outer mapped words, includes the inner filtered words. I then was left with an array with duplicates, and empty values. So I created a reduce that checked to make sure it was not empty && not included in the accumulator array, if this was true I returned [...acc, i[0]] (because of the filter inside the map, each word string was subnested in it’s own array), and if it was not true, I just returned the acc.

Then I sorted the return. I did not use variables, I just called the function straight on what the previous function returned, but instead of keeping it on one line, I put it on multiple lines for better readability.

What I learned from other people’s code:

I see someone use a Array.prototype.some(), I have never seen this before. I tried the every, but that didn’t work, because it was only partly equal. So the .some() seems to be what I was looking for. Seems to be similar to the ruby any. Others used .match(), to see if the largerWord.match(smallerWord). Interesting, because normally I’ve seen that used with regex.

Array.prototype.find() also seems it is more useful than filter, because it will stop as soon as it finds one, which will avoid our duplicate issue, and will keep processing time down.

Someone else converted the larger string array into one long string separated with spaces by word, and then was able to check for indexOf on the first word. Very interesting, and this was only one filter! No inner loops.

It’s amazing how people think!

I’ve learned a lot today, looking forward to tomorrow!

Day 22 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/how-many-feelings/javascript

Time: 15 minutes

What I’ve learnt: Let me start by saying, Javascript needs a uniq built in function! I spent 7 minutes on the method, and then another 7 minutes on looking for a Javascript uniq function, before having to build my own. I tried to use the lodash _.uniq(array) but it didn’t work!

Anyways, so we had to check a string for particular words in an array. So I used a forEach loop to iterate through the array of words, and in the forEach I filtered on the string that was passed in (by using .split("") to turn it into an array), and it was filtered if a letter in the the string was included in the wordArray.

I then compared this newly created variable’s length (with my external uniq function) against the word.length, and if they were equal then we clearly had all the letter’s in the string, and upped my counter of matchedFeelings to keep track of the amount of words found.

My uniq method took in an array, reduced over the array and if the accumulator did not include the current letter we are currently iterating over then we pushed it into the accumulator, and returned the accumulator whether or not it includes the character.

I then checked with a ternary if my counter was === 1, if it was 1 I returned “1 feeling”, and if not I returned ${counter} feelings.

What I learned from other people’s code:

Many have used .every on an array. I have never heard of this. What this method does it checks if every one of these elements meet a certain condition. array.every(<condition to be met>). So I would do string.split.every(i => string.includes(i)) I would have been able to increment my counter if that was true, instead of needing my uniq. Nice to know Javascript has some helpful built in methods!! Every, every, every, need to remember this one!

Until tomorrow! 

Day 21 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.
Time: 150 minutes (I know, this is long!)
What I’ve learnt: So to be honest, I thought this would be way simpler than it seemed, but since I started I had to go through with it. The math on getting a common denominator is much harder in programming than it was in grade school!
So the first thing I did was create a reduce with in an initial acc `[1, []]` of  that iterates through the lst passed in (which is an array of fractions) and multiplies the denominator (fraction[1]) to the acc[0], and pushes the denominator into the acc[1] array. So at the end of this array I have the product of all the denominators multiplied by each other, and an array holding all the possible denominators.
I then created a getLCD function that takes in the product of all the denominators, and the array of all the denominators that I got from my reduce. I sorted the denominator array, and then created a filter inside of a for loop based on the arrayOfDenominators.length that checks if each of the denominators is divisible by that denominator we are currently iterating through in our for loop. If they all are divisible, then I divided the greatest common denominator by that number, and reassigned that gcd that was originally passed in as a parameter. I then iterated through a newly created array of 2-9, and checked again to see if we can lower the denominator further.

Now that we have the LCD, I used a created a function `refactorFactions` that takes in the LCD, and a specific fraction, and it divides the lcd/denominator assigned to a variable multiply, and then returns a string or the numerator * multiply and denominator * multiply.

The above function was called in a reduce that added the strings to the accumulator to return the final string.

Pheeew. All green. I just need to show you after all this hard work!!
What I learned from other people’s code: So I knew there would be a better way to get the LCD with recursion, but even now I can’t fully understand it. Here is a nice blog on it. https://www.w3resource.com/javascript-exercises/javascript-math-exercise-10.php. I need to do this line by line, but my brain is totally fried! So I’m going to have to relook at this, and maybe blog about it in a future post.
What a day! 😰 But at least there was a happy ending!

Day 20 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/moving-zeros-to-the-end/

Time: 10 minutes

What I’ve learnt: So this was a 5KYU and labeled as an interview question. It didn’t look that difficult, but I thought it must be harder. Happy to say, I must be improving because it was not very hard.

I took the array we were given in, and filtered this based on values !== 0and assigned this to a variable to use later on. Then I created a for loop to iterate as many times as the difference in length between the original array, to the newly filtered array, and passed in 0 to a newly created array assigned to it’s own variable.

And then I returned the two arrays combined with the spread operator `return […newArray, …zeroArray]`

What I learned from other people’s code: Ok, so silly me, I didn’t need a for loop for the 0’s, I could have just used two filters, one for everything but 0’s and then one for only 0’s and concatenated these two all in one line! But more or less the same idea!  I thought someone would do something with regex, but I didn’t see any.

See you tomorrow!

Day 19 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/counting-duplicates/javascript

Time: 10 minutes

What I’ve learnt: First things first I made all letters lowercase, and split it into an array of sorted letters. I wanted to use a reduce, and decided I needed to keep track of the previous letter, as well as letters that were already marked duplicate, because I need to make sure not to duplicates multiple time on the same letter. So I passed in the initial value of the reduce to look like `{prevLetter: “”, dupsArray: []}`.

Then in each iteration of the reduce I checked if the previous letter was equal to the accumulator.prevLetter && that it was not included in the accumulator.dupsArray, if both these conditions were met I added it to the accumulator.dupsArray. Then I reset the prevLetter to the currentLetter,  and returned the new accumulator.

Once this finished I just needed to return the reduce.dupsArray.length. All done 🙂

What I learned from other people’s code: It is interesting how people used regex to check for dups. `match(/([^])\1+/g)` I’ll have to play with that on a regex site!

And onto the next 🙂

Day 18 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/sum-of-a-nested-list/javascript

Time: 60 minutes

What I’ve learnt: So I spent time doing this one (even though it is a kata 7, it took me a while because I wanted to do it without too many conditionals. After some trial and error of trying to create a reduce method that would flatten the array (which on some conditions would need to have been done recursively because they were nested), I decided to simple join the array into a string.

This gave me a string with commas, so I just ignored the commas with a match using some regex. Yay!! I finally used regex! Match returned me an array of numbers so I can reduce it down to it’s sum. I needed to add in a ternary to check if the array converted to a string without commas was undefined , because otherwise calling reduce on that would fail.

What I learned from other people’s code: I saw a lot of recursion, where in their reduce they checked if Array.isArray, and then if it was they did recursion on that array to the entire method, which built up a stack for the reduce to sum up. And someone used lodash _flatten!

Have a good one!

Day 17 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/string-array-revisal/javascript

Time: 30 minutes

What I’ve learnt: This was done at my weekly javascript meet-up. Thanks for everyone’s awesome ideas! So again, string manipulation. I will expect to see regex in the solution. 🙂 But at this meeting, we were using our more comfortable conditionals. Pretty standard manipulation, and adding onto a string within a for loop to get this kata solved.

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function dup(stringArray) {
  let result = [];
  for (let i = 0; i < stringArray.length; i++) {
    let previousLetter;
    let newStrings = stringArray[i].split('')
    
    newStrings.forEach(letter=> {
      if (!previousLetter) {
        result[i] = letter;
      } else if (letter !== previousLetter) { 
        result[i] += letter;
      } 
      previousLetter = letter;
    })
  }
  return result;
};

 

What I learned from other people’s code:

So as I expected, I see some replace with regex 🙂 This is definitely something we are going to have to do at a future meet-up. It’s amazing how they can conquer so much, in so little code. But until I start playing with it more it feels so untouchable! Add to the TODO: regex!!

Have a good night all 🙂

Day 16 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/prize-draw/

Time: 60 minutes

What I’ve learnt: So I was super surprised that this one took me an hour (with some breaks in between doing other stuff)!  But I was really thinking of a way to store the winner, before I full read the kata I thought I was just storing one winner so I wanted to create an array of the winner, so as I iterated I could store the highest scoring winner along with their name, so I tried

array[0], array[1] = <name>, <score>

and sadly that did not work (it works in ruby!). So then I changed it to `array = [<name>, <score>]`, and that worked, but then I realized I need all the names in order so I could choose the n number of them and return that one.

Sooooo, I decided an array of objects is my best bet, and tried this array.push({name: score}), only to realize that I can’t use a variable name as a key in the object like that. So again learning new things. (And this sounded like an easy kata lol). So the way to do that was to put a bracket around name: {[name]: score}, but by then I had already changed my mind and thought it would look cleaner (and easier to sort!) if I named it like this: `array.push({name: <name>, score: <score>})`.

So now after a for loop, split(""), reduce, with charCodeAt -96 (all the letters were converted `toLowerCase()`, and then * by the `weight[i]` I had my `score` (and name was from the array.split("")[i]) to push in the winners array.

Now I created a variable and did `winners.sort(a, b =>  a.score > b.score)`, and it was interesting to see that sort mutated the winners array, so got rid of the variable and continued using the mutated array. So I first sorted by name, and then by score, and all was good in the world until I got to the final tests, and the random tests were failing. And for some reason, my arrays were not all being sorted :(.

[ { name: ‘Olivia’, score: 444 },
{ name: ‘Elizabeth’, score: 485 },
{ name: ‘Matthew’, score: 485 },
{ name: ‘Lagon’, score: 162 },
{ name: ‘Addison’, score: 365 },
{ name: ‘Robert’, score: 420 },
{ name: ‘Olivai’, score: 444 },
{ name: ‘Lily’, score: 372 },
{ name: ‘Lyli’, score: 310 },
{ name: ‘William’, score: 344 },
{ name: ‘Willaim’, score: 344 },
{ name: ‘Noah’, score: 84 },
{ name: ‘Grace’, score: 156 },
{ name: ‘Abigail’, score: 288 },
{ name: ‘Sofia’, score: 165 },
{ name: ‘Madison’, score: 328 },
{ name: ‘Sophia’, score: 148 },
{ name: ‘Liam’, score: 117 },
{ name: ‘Ava’, score: 108 },
{ name: ‘Avery’, score: 76 },
{ name: ‘James’, score: 53 },
{ name: ‘Daniel’, score: 51 },
{ name: ‘Aiden’, score: 38 } ]

So I had to get a better sort going, though I am not really sure why this didn’t work on the random tests, but the initial tests it was fine on. So I literally returned where each position should go based on if statements:

1
2
3
4
5
6
  winners.sort((a,b) => {
    if (a.score == b.score) return a.name.toLowerCase() > b.name.toLowerCase()
    if (a.score < b.score) return 1
    if (a.score > b.score) return -1;
    return 0;
  })

 

And then returned the winners[n-1].name and we were flying green!!!

So I think I’ve learned about objects, and sort in this lab. Though I will need to follow up why the built in did not work for me.

What I learned from other people’s code:

So I did see that people did have to hack into their sort method. I’ve gotta say I’m pretty happy with my solution overall, and see I did not overcomplicate things. It’s interesting to note how in some people’s sort() they use a.score – b.score. This will return either a positive or negative number so that will tell it where to place it. Very nice! (Here’s a nice link on sorts – http://www.javascriptkit.com/javatutors/arraysort.shtml)

Happy learning until tomorrow!

 

 

Day 15 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-simple-version

Time: 10 minutes

What I’ve learnt: This kata I started with a for loop on the ranges. I then created a new array based on the start and end range (range[0], range[1]) with slice as not to manipulate the old array (because we will use it on each range!). Then I reduced this new array to get the total. (Hurray for using reduce!). I then created a variable outside the loop called maxSum, and set it equal to nothing (originally I had it equal to 0 but that broke my code as sometime it is a negative number), then I had a conditional checking if the current sum (from the reduce) was greater than the maxSum (or if maxSum was undefined for the first iteration), and if sum was greater replace maxSum with the current sum. And as the final return before the function closed out I returned maxSum. I knew I could have wrapped the entire loop (instead of the for loop) in a filter, but I felt the code was less readable to I kept it in a for loop.

What I learned from other people’s code:

Some people really love to concise everything down to one line. And I really thought it was amazing. But I think I would rather keep my code readable, so when I came back to it after some time, I would be able to understand it quite quickly. Some mapped it into an array (instead of my outer for loop) and called Map.max on the map, that is cool 🙂 Slice and reduce was used in most, so I’m feeling happy with my code.

Half way through! See you tomorrow!

Day 14 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/reverse-words/javascript

Time: 15 minutes

What I’ve learnt: So this was a relatively easy kata, something I have done before. And I put in my solution and it wouldn’t pass, and was quite confused for a few minutes, until I realized there were no initial tests and I had to create them! So I used Test.assertEquals(functionToBeCalled, ExpectedReturn, ‘Description of test’). I used a map here, and joined them right back to be a string after my map, instead adding to a variable holding through the string as it loops.

Here was my solution:

1
2
3
function reverseWords(str) {
  return str.split(" ").map((word)=> {return word.split("").reverse().join("")}).join(" ")
}

 

What I learned from other people’s code:

I think most people did almost identical to mine. In fact there are 328 grouped as having done the kata like that. Someone others split the whole thing without space (by letters), reversed everything, then joined back together, split again by space and then did one more reverse to put the words back in order. That is definitely an out of the box way to think about such a problem.

I hope my javascript is improving! Until tomorrow 👋

 

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner