RunJS LogoRunJS

10 JavaScript Snippets for Solving Common Problems

Published on

useful JavaScript snippets

Utility libraries are great but sometimes they can be overkill. This is especially true when you're only looking for a simple solution to a common problem.

In this article, I've put together a list of common problems that JavaScript developers often face and the snippets you can use to solve them.

1. Create an array of key-value pairs from an object

This example uses the keys method from Object and the map method from Array to map over an Object’s keys and create an array of key-value pairs.

const keyValuePairsToArray = (object) =>
Object.keys(object).map((key) => [key, object[key]]);
// Example
keyValuePairsToArray({ JavaScript: 1, Playground: 2 });
// [ ['JavaScript', 1], ['Playground', 2] ]
keyValuePairsToArray({ x: 1, y: 2, z: 3 });
// [ ['x', 1], ['y', 2], ['z', 3] ]

2. Remove falsey values from an array

The Array filter method is used here to cast all values of an array as a boolean and create a new array of only truthy values.

const compact = (arr) => arr.filter(Boolean);
// Example
compact([false, 5, "", 10, "b", "m" * 23, 0, NaN, "q", 1]);
// [ 5, 10, 'b', 'q', 1 ]

3. Get the difference in days between two dates

The start date is subtracted from the end date to get the difference in seconds. The difference is then divided by the number of seconds in a day to get the difference in days.

const getDaysDiffBetweenDates = (startDate, endDate) =>
(endDate - startDate) / (1000 * 3600 * 24);
// Example
getDaysDiffBetweenDates(
new Date("2022-12-13"),
new Date("2022-12-22")
);
// 9

4. Find the difference between two arrays

This solution creates a set from one array which is then compared against the other array using the Array filter method. The use of Set here is an optimisation that is more efficient when dealing with larger arrays.

const difference = (a, b) => {
const set = new Set(b);
return a.filter((item) => !set.has(item));
};
// Example
difference([1, 2, 3, 4, 5], [1, 2, 4]);
// [3, 5]

5. Convert an array to CSV

The Array map method is used to iterate over each level of the array and join each value with a defined delimiter.

const arrayToCSV = (arr, delimiter = ",") =>
arr
.map((row) => row.map((value) => `"${value}"`).join(delimiter))
.join("\n");
// Example
arrayToCSV([
["one", "two"],
["three", "four"],
]);
// '"one","two"\n"three","four"'

6. Count the occurrences of an item in an array

The Array reduce method is used to loop over the array and increment an accumulator value each time the target value matches the current value.

const countOccurrences = (arr, targetValue) =>
arr.reduce(
(acc, value) => (value === targetValue ? acc + 1 : acc),
0
);
// Example
countOccurrences([1, 2, 2, 1, 2, 2, 3, 3], 2);
// 4

7. Capitalize the first letter of a string

The string is cast to an array and deconstructed. The first element in the array is the first letter and the toUpperCase method is used to convert it to uppercase while the rest of the array is joined as a string.

const capitalize = ([first, ...rest]) =>
first.toUpperCase() + rest.join("");
// Example
capitalize("javaScript");
// 'JavaScript'
capitalize("playground");
// 'Playground'

8. Get the largest numbers in an array

The Array sort method is used to order the arraying into descending order. The slice method is then used to extract the first elements, which will be the highest numbers.

const maxNumbers = (arr, number = 1) =>
[...arr].sort((x, y) => y - x).slice(0, number);
// Example
maxNumbers([1, 2, 3, 4, 5]);
// [5]
maxNumbers([7, 8, 9, 9], 2);
// [9, 9]

9. Average an array of numbers

The Array reduce method is used to loop over the items in an array and add each value to an accumulator. The accumulated value is then divided by the number of items in the array, producing an average.

const average = (numbers) =>
numbers.reduce((acc, value) => acc + value, 0) / numbers.length;
// Example
average([9, 10, 11, 12]);
// 10.5
average([6, 7, 8, 9]);
// 7.5

10. Check if a string is valid JSON

The JSON parse method is used to parse the string to JSON and if it is invalid, an error will be thrown. The try-catch statement is used to catch this error and return false and otherwise true.

const isValidJSON = (str) => {
try {
JSON.parse(str);
return true;
} catch (err) {
return false;
}
};
// Example
isValidJSON('{"name":"John","age":30}');
// true
isValidJSON('{name:"John",age:30}');
// false

Final thoughts

I hope you've enjoyed reading this article and found it helpful. If you'd like to try out any of the code snippets listed above, an easy way to do this is by using RunJS. RunJS is a JavaScript playground available for Mac, Windows and Linux. It runs your code like a REPL, giving you instant feedback while you type as well as a host of other powerful features. Give it a try.

TwitterShareFacebookShareLinkedInShareRedditShareY CombinatorShare

Join the RunJS mailing list

You'll receive an occasional newsletter with development updates and articles from the blog. Unsubscribe at any time.

Recent posts