trivago tech tips - #1 JS Edition
Five fun, quick, and easy ways to improve your JavaScript programming skills
This week we’re starting a new series, #trvtechtips, where we’ll focus on one technology per week and share a daily tip or learning with you. This week is JS week and we’ll be adding a new tip every day until Friday – stay tuned 🤖
#1 How to get all unique items in an array:
Detailed explanation:
An array in JavaScript can have duplicates. 👯
Sometimes you want a quick way to filter those out and keep the unique elements only.
Now you could go and loop over all elements and collect them into a new array by checking each element one by one like so:
var a = [];
for (var i=0, l=arr.length; i<l; i++) {
if (a.indexOf(arr[i]) === -1) {
a.push(arr[i]);
}
}
// Unique elements in `a`
This code works but it's quite verbose.
There's also a more important efficiency problem. The first solution has time complexity O(n^2) while the Set solution has time complexity O(n).
(Thanks to our reader rolaviw209 for pointing that out in the comments.)
Let’s compare it with our version from the tech tip:
const unique = list => [...new Set(list)]
This converts the array into a `set`, which is a datastructure with only unique elements.
After that, the set gets expanded again into an array. That's what the `[...x]` syntax is for.
Out comes our new array of unique elements.
Use it like so:
// Define the function
const unique = list => [...new Set(list)]
// Call it on an array
unique(["❤️", "💻", "☕", "⚙", "🐧", "🐧"])
// This returns
[ "❤️", "💻", "☕", "⚙", "🐧" ]
#2 Avoiding a form submit on a button
Often we reach for a
event.preventDefault()
to prevent a button element from submitting a form. A simpler solution to that is to change the type
of the button:
<button type="button">I won't submit the form</button>
#3 Measure the time used by an operation
We can measure how much time passed between a console.time() and a console.timeEnd():
#4 Character frequency in a string
Wanna know character frequency in a string in a fancy way?
Let’s look at the code in more detail. Here is the full snippet again:
[..."hello"].reduce((total, letter) => { total[letter] ? total[letter]++ : total[letter] = 1; return total }, {}); // {h: 1, e: 1, l: 2, o: 1}
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. [See Mozilla Developer Guide]
It creates an array of our characters like so:
[ 'h', 'e', 'l', 'l', 'o' ]
This is the input of reduce
, which executes a reducer function (that you provide) on each element of the array, resulting in single output value. It has the following structure:
(accumulator, currentValue) => { }
The accumulator “gathers” all values and gets returned at the end. In our case, the accumulator is called total
. The currentValue
is the single letter in our case. For each letter in the input, we check if it already exists in total
. If it does, we increment the count by one and if not, we set the count to 1.
Basically we keep track of the letters we saw as we iterate over the string.
Oh, and one more detail! The initial value is an empty dictionary {}
. That’s our starting point and the data-structure we initialize total
with in the very beginning.
The final output is a dictionary/map of counts for each character in the input. Neat, huh?
#5 Giving names to your console.log()
Just a handy way to save some typing, when using multiple console.log().
To not lose track in the console which log is which, you can give it a name like so:
const name = 'Cagri';
console.log('name: ', name);
Or you just the shorthand syntax for objects:
const name = 'David';
console.log({ name });
Which will create an object with the key name
and its value 'David'.
Hope you found our five tips for Javascript to be helpful! Keep an eye out for our next series about CSS coming soon 👀
#trvtechtips
"This code works but it's quite verbose." There's also a more important efficiency problem. The first solution has time complexity O(n^2) while the Set solution has time complexity O(n).