Practical Javascript Array Cheat Sheet

Photo by Paul Teysen on Unsplash

Javascript is undoubtedly widespread by now. Web is full of them. It is getting more accessible as well. Plenty of resources are available for anyone willing to learn. Tutorials, courses, forums, books, boot camps, all tried to make us able to make a working application from scratch.

But in my experience as mentor at Binar Academy, those jungle of knowledge is overwhelming for some. So I figured out that there should be condensed version of learning material. Furthermore, it should be both conceptual and practical. Javascript array is fine example. We use them a lot. So in this article, I assembled a list of common tasks of Javascript array manipulation. Hopefully, this can be helpful for Javascript developers.

Please do mind that this article will not mention built-in Javascript array functions. You can find them here or here. I’m talking about common use cases like finding maximum value of an array, deleting duplicates, etc. Practical things useful in many projects.

As convention, I’m going to use regular function declaration with array(s) and some parameter. The output might be single value, an array, or arrays. Now, please enjoy my assortment of practical use cases using Javascript array.

Given an array of numbers, find the maximum or minimum value of an array.

// get minimum value of an array
function minValueArray(arr) {
return Math.min.apply(null, arr);
}
// get maximum value of an array
function minValueArray(arr) {
return Math.max.apply(null, arr);
}

Given an array, get its last element. Actually, I’m quite surprised there’s no built-in function like array.end() in PHP or array[-1] in Python. So it made its way into my list. There are two “safe ” (a.k.a non-mutating) approaches: count from its length or using .slice.

// get last element of an array
function lastElement(arr) {
return arr[arr.length - 1]
}
// ORfunction lastElement(arr) {
return arr.slice(-1)[0]
}

Either choice is sufficient to get last element of any array. The first is considered faster, but the second can be attached nicely to other manipulation functions. For example, I have an URL “https://random.url/with/some/id_123”. If I need to get URL params (‘id_123’) without additional library, I can convert it to array with .split method, then pick the last element.

function getParams(urlString) {
return urlString.split('/').slice(-1)[0];
}

Giv en an array of numbers, find the sum of its numeric elements. This includes two versions: naive version where we consider the input will always be array of numbers, and more realistic approach with validation and error handling (because users love to ruin our perfect array).

// get sum of numbers in array
function sumNumbers(arr) {
var result = 0;
for (var i=0; i<arr.length; i++) {
// we assume each element is always a number
result += arr[i];
}
return result;
}
// get sum of numbers in array - realistic approach
function sumNumbersRealistic(arr) {
// only add if the element exist and translatable into number
var numbers = arr.filter(Number);
var result = 0;
for (var i=0; i<numbers.length; i++) {
result += parseInt(numbers[i]);
}
return result;
}
//====================================================var sample = [1,2,null,'-1','0',3,]
console.log(sumNumbers(sample)); // 3-103
console.log(sumNumbersRealistic(sample)); // 5

Given an array of strings, find the longest element (i.e most character count). There is possible case where there are more than one longest elements. We will separate algorithm for each case below.

// get the FIRST longest element in array of strings
function longestElement(arr) {
return arr.sort((a, b) => { return b.length - a.length; })[0];
}
// get ALL longest elements in array of strings
function longestElements(arr) {
let maxLength = arr.reduce((a,b) => a > b.length ? a : b.length, 0);
return arr.filter(element => element.length == maxLength);
}

Given an array, return a random element in that array.

// get random index of an array
function getRandomIndex(array) {
return Math.floor(Math.random()*array.length))
}
// get random element of an array
function getRandomElement(array) {
return array[Math.floor(Math.random()*array.length))]
}

Given an array and search term, return new array containing elements that match the search term.

// get the index of FIRST match
function findString(term, arr) {
for (var i=0; i<arr.length; i++) {
if (arr[i].match(term)) return i;
}
return -1;
}
// get the elements of ALL matches, return -1 if not found
function findAllString(term, arr) {
let result =[];
for (var i=0; i<arr.length; i++) {
if (arr[i].match(term)) {
result.push(arr[i]);
};
}
if (result.length > 0) {
return result;
} else {
return -1;
}
}

Given a function with parameter, checks if it’s an array. Return true (or continue) if it is an array, otherwise stop.

function stepsWithArrayValidation(arr) {
if (!Array.isArray(arr)) return -1;
return true; // or continue your code
}

Given an array, return new array with duplicated elements removed, leaving it as array of distinct values. Personally, I like the elegance of this approach.

// return array of distinct elements, no more duplicates
function removeDuplicates(arr) {
return [...new Set(arr)]
}

Given an array, return the same array with additional element(s). The key is using method that does not mutate original array. .push() method mutates array, so we will need other approaches. This method is desirable if you have array state in React, where immutability is primary concern.

// add an element to array without mutating
function addWithoutMutate(arr, element) {
return arr.concat(element)
}
// or
function addWithoutMutate(arr, element) {
return [...arr,element]
}
// add an array of elements to array without mutating
function addWithoutMutate(arr, elements) {
return [...arr, ...elements]
}

Given an array, remove empty elements. Now, we might need to be more specific about what “empty” means. It could be 0, “”, [], {}, null, or undefined. In this case, want to remove null or undefined elements. Then, it returns filtered array.

This can be useful when we need clean array to work with. In most cases, we don’t want to deal with null or undefined value throughout business logic. It will break things somewhere.

// remove null or undefined array elements
function removeNullElements(arr) {
return arr.filter((e) => {return e != null});
}
//======================================================var sample = [1,,,null,"",2,0,,{},-1,undefined,-2,[],false,];
console.log(removeNullElements(sample));
// [ 1, '', 2, 0, {}, -1, -2, [], false ]

Given a desired length, return an empty array with that length. For example, if we call makeArray(5), we wil have [undefined, undefined, undefined, undefined, undefined]. It can be useful when we need to specify container of values with fixed length. This way, we can assign value to specific index immediately.

// make empty array with specific length
function makeArray(length) {
return Array.apply(null, Array(length));
}
// OR with ES6
function makeArray(length) {
return Array.from({ length: length });
}
//======================================================var sample = makeArray(3); // [undefined, undefined, undefined]
console.log(sample.length) // 3
sample[1] = 'yes' // [undefined, 'yes', undefined]

There’s more to come. I’ll keep up with more use cases later. If you have feedback or ideas, please don’t hesitate to tell me.

I am Yogi Saputro, a full stack developer at Pinjammodal.id and full stack development mentor at Binar Academy. I’m also passionate in building data architecture and provide value to businesses. Check out my other stories to find out more.

Software developer with MBA degree, mentor, somewhat fatherly figure, data and business synergy enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store