Practical Javascript Array Cheat Sheet

Yogi Saputro
6 min readOct 12, 2020
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.

Maximum/minimum value of 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);
}

Access Last Element of Array

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];
}

Sum of numbers in Javascript array

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

Longest element in Javascript array of strings

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.

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

In theory, the first approach has O(n log(n))time complexity from sort method. The second approach is better with O(n)time complexity.

Select Random Element in Javascript Array

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))]
}

Finding elements that match search term in array of strings

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;
}
}

Javascript array parameter validation

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
}

Remove duplicates or get distinct elements in Javascript array

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)]
}

Add elements without mutating the array (useful for React state)

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]
}

Remove null or undefined elements in Javascript array

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 ]

Declare empty array with specific length

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]

Add Array Element on Specified Index

Javascript has push() to add array element to the end.unshift() is available to add new element to the beginning of array. What if you need to add new element at specific index of an array? Well, splice() got your back!

// Add array element on specific index
function addArrayElement(arr, idx, element) {
return arr.splice(idx, 0, element);
}
// =========example===========
let example = [1,2,3,4,5]
addArrayElement(example,3,3)
console.log(example)
// [1,2,3,3,4,5]

Remove Array Element on Specified Index

The next useful pair is removing array alement on specified index. Just like before, splice() can save the day.

// Remove array element on specific index
function removeArrayElement(arr, idx) {
return arr.splice(idx, 1);
}
// ========example========
let example = [1,2,3,4,5];
removeArrayElement(example, 2);
console.log(example);
// [1,2,4,5]

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.

--

--

Yogi Saputro

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