Recreating Ruby Features in Javascript
Switching between Ruby and Javascript can be challenging at first. Several native features of Ruby are not available right away in Javascript, but here are implementations of three public Ruby methods to ease the transition:
1. Compact
In Ruby, the array method .compact filters falsy values from an array. For example:
["apple", "banana", nil].compact# => ["apple", "banana"]
Javascript does not have a comparable feature but we can accomplish the same with a simple filter:
["apple", "banana", false].filter(Boolean)// => ["apple", "banana"]
How does this work? Javascript allows for the passage of parameters to the Boolean object, which returns true or false, perfect for a filter. Warning: Ruby and Javascript have different definitions of truthiness. For example, both 0 and an empty string are falsy in Javascript, but truthy in Ruby.
2. Counting with Hashes
Javascript objects and Ruby hashes are similar, allowing you to store key value pairs — a great tool for counting. In Ruby, you can give a hash a default value (like 0), helpful for incrementing. For example:
counter = Hash.new(0)
array = ["apple", "banana", "banana", "orange"]array.each { |el| counter[el] += 1 }counter# => { "apple"=>1, "banana"=>2, "orange"=>1 }
Javascript doesn’t allow you give an object a default value, but you can still use objects to count. For example:
const counter = {};
const array = ["apple", "banana", "banana", "orange"];array.forEach((el) => {
counter[el] ? counter[el] += 1 : counter[el] = 1;
});counter
// => {apple: 1, banana: 2, orange: 1}
3. Uniq
Ruby allows you to simply filter duplicate values from an array using .uniq. For example:
["apple", "banana", "banana", "orange"].uniq# => ["apple", "banana", "orange"]
This is not so easy in Javascript, but it can be accomplished using .filterwith a callback. Here’s an implementation:
['apple', 'banana', 'banana', 'orange'].filter((element, index, array) => array.indexOf(element) === array.lastIndexOf(element));// => ["apple", "orange"]
Let’s break it down. Javascript’s filter can accept three arguments: each element of an array, that element’s index, and the array itself. By checking if the index of an element is the same as its last index, you can see if an element is only listed once. If this isn’t the case, the element is removed from an array.
Get Adam Cohn’s stories in your inbox
Join Medium for free to get updates from this writer.
In the above example, the first banana has an indexOf 1, but a lastIndexOf2, so it is removed from the array. The second banana then has an indexOf 1 and a lastIndexOf 1, so it is left untouched.







