JavaScript Tricks to Save Time & Frustration

Sharing is Caring

In my everyday life as technology leader (“tech lead”) and full stack developer I run into a lot of problems that need to be solved every day. A lot of Junior and Intermediate developers struggle with some of these problems, so hopefully this article will help you as you work and grow.

Extracting Unique Values

According to Wikipedia “a set is an abstract data type that can store certain values, without any particular order, and no repeated values.”

The Set data structure is a great way to force all values to be unique, and thankfully the Set was added as part of ES6 along with the spread operator. This means we can very easily create a new Array with only unique values with only one line of code.

const myArray = ['a', 'a', 'b', 'b', 'c', 'd', 'e']
const uniqued = [...new Set(myArray)];

console.log(uniqued)
// Results in: ["a", "b", "c", "d", "e"]

Converting a String to a Number

In JavaScript, strings can be used to represent an actual number ’42’ versus 42. The reason this becomes a problem is when we try to do strict comparisons it will fail.

For example this code looks like it would write ‘did this work?’ to the console, but it won’t because of the strings.

let numberAsString = '42'
let actualNumber = 42

if (numberAsString === actualNumber) {
  console.log('did this work?')
} else {
  console.log('nope it wont work because of the strict comparison!')
}

There’s at least three different ways we can safely convert the string to a number.

parseInt

parseInt() is used to convert a string to a whole number. It accepts two potential parameters although, I only normally use the first parameter which is the string. The second parameter is the base number used in mathematical systems which should normally be 10.

ie: parseInt(myNumberString, 10)

parseFloat

parseFloat() converts a string into a decimal number (aka a point number). It accepts strings with random text in them and will return the number. For example:

let piString = '3.14159 is the value of pi'
console.log(parseFloat(piString))

// returns 3.14159

Keep in mind that the number has to be at the start or it will return NaN. For example:

let piString = 'the value of pi is 3.14159'
console.log(parseFloat(piString))

// returns NaN

Number

The Number method converts a string to a number. The number method can return an integer or return a floating point number, so it shouldn’t be used where consistency can be important.

Number can be a better choice if you want errors when someone passes a string that potentially has unexpected letters in it.

Shuffling or Sorting Elements in an Array Alphabetically

For the most part, with arrays sorting can be done really easily by calling sort().

'use strict'

const myArray = ['a', 'e', 'c', 'q', 'z']
console.log(myArray.sort())

// returns [ 'a', 'c', 'e', 'q', 'z' ]

Reversing an array is also just as easy, you can call a .reverse method. Like so:

'use strict'

const myArray = ['a', 'c', 'e', 'q', 'z']
console.log(myArray.reverse())

// returns [ 'z', 'q', 'e', 'c', 'a' ]

In the real world, as we all know, this is rarely good enough. Using a comparator function we can better control the sorting. For example, say I was writing software at a bank and needed to offer sorting by the last name and the account balance.

I would end up implementing my sorting in a way similar to this.

'use strict'

const data = [{
  last_name: 'Burnett',
  first_name: 'Earnestine',
  account_balance: 100
}, {
  last_name: 'Watson',
  first_name: 'Timmothy',
  account_balance: 391
}, {
  last_name: 'Gross',
  first_name: 'Jewell',
  account_balance: 31
}]

const sortedByLastName = data.sort((a, b) => {
  const aLastName = a.last_name.toUpperCase()
  const bLastName = b.last_name.toUpperCase()

  let comparison = 0
  if (aLastName > bLastName) {
    comparison = 1
  } else if (aLastName < bLastName) {
    comparison = -1
  }

  return comparison
})

console.log(sortedByLastName)

const sortedByAccountBalance = data.sort((a, b) => {
  let comparison = 0
  if (a.account_balance > b.account_balance) {
    comparison = 1
  } else if (a.account_balance < b.account_balance) {
    comparison = -1
  }

  return comparison
})

console.log(sortedByAccountBalance)

Shuffling Elements in an Array

JavaScript doesn’t have a default way to shuffle arrays unlike other languages like PHP. I’ve been using the knuth shuffle for quite a while whenever I needed to do random ordering.

'use string'

// this uses the knuth shuffle algorithm
const shuffle = function (array) {
  let currentIndex = array.length
  let temporaryValue, randomIndex

  // While there remain elements to shuffle...
  while (currentIndex !== 0) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex)
    currentIndex -= 1

    // And swap it with the current element.
    temporaryValue = array[currentIndex]
    array[currentIndex] = array[randomIndex]
    array[randomIndex] = temporaryValue
  }

  return array
}

// To use you just pass in your array

The only problem with this function is that it will mutate the array that’s been passed in. To get around that you can pass in a cloned version using myArray.slice() or something.

Replace All Substrings in a String

Probably one of the things that took me the longest time to understand in JavaScript was that there’s no replaceAll function on the string object in JavaScript.

I’ve spent a lot of time using crazy loops and mutating the string constantly as it iterated to do the replace. Eventually, I realized I could use a regular expression (regex).

Using the global operator “/g” it’s possible to replace all of the characters in a string. Say I wanted to replace “abc” in the below code.

'use strict'

let originalstring = 'Test abc test abc test test test abc test test abc'
const replacedString = originalstring.replace(/abc/g, '')

console.log(replacedString)

// results in Test test test test test test test

In turn, if you wanted to create a function that did this you could use something like this:

function replaceAll(str, find, replace) {
  return str.replace(new RegExp(find, 'g'), replace);
}
Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.