Cheatsheet of arrays on Javascript

Cheatsheet of arrays on Javascript.

Because Javascript tables are always present in development and are the source of many questions for beginners or when it comes to manipulating them in depth, here is a short list of recurring methods and uses when developing in Javascript.

The article will be divided into groups of methods ranging from the simplest and best known to the most specific and incongruous. Some tricks require the use of external libraries, whose installation is recommended in particular cases requiring fine processing or to make the code easier to read.

At the end of the article, you’ll also find a download link for a PDF cheatsheet listing all the tips and tricks highlighted in this article.

You can add items to the list at any time, so don’t hesitate to share your other techniques if you wish.

The basics of manipulating arrays in Javascript.

Create and add javascript array.

The main technique for add javascript array is to use a literal expression. The array is instantiated with defined values:

const array = [1, 3, 6, 9];
var array = [1, 3, 6, 9];

Create and add javascript array with its Array() expression and no initial value:

var array = new Array();
array[0] = 1;

Declare array js from an iterable object (e.g. a character string):

var string = ‘1369’;
console.log(Array.from(string)); // [‘1’, ‘3’, ‘6’, ‘9’]

Construct and add javascript array from arguments with .of(). Be careful not to confuse this method with creating an array with Array(). Here, the arguments define the value of the elements, whereas for Array(), the size of the array is defined in the first argument:

var array = Array.of(1, 3, 6, 9);
console.log(array); // [1, 3, 6, 9]

Empty a javascript table.

Use an array size of zero to empty the contents of a javascript array:

var array =  [1, 3, 6, 9]
array.length = 0;

Empty a javascript array by declaring an empty array and replacing the elements present:

var array =  [1, 3, 6, 9]
array = [];

Use the splice() method to completely or partially empty a javascript array and its contents:

var array =  [1, 3, 6, 9]
array.splice(0, array.length);

Adding and deleting elements in a javascript table.

To add a string, number, array or other type of variable to a javascript array, the push() method is the most commonly used:

var array =  [1, 3, 6, 9];
array.push(11); // [1, 3, 6, 9, 11];

A variant is the unshift() method, which works in a similar way, but this time adds the new element to the beginning of the array:

var array =  [1, 3, 6, 9];
array.unshift(11); // [11,1, 3, 6, 9];

Note that it is possible to use .unshift() to add several elements in the form of arguments separated by a comma.

Note that .unshift() not only adds elements, but also returns the size of the array after addition.

Delete the last element of a javascript array using the .pop() method:

var array =  [1, 3, 6, 9];
array.pop(); // [1, 3, 6, 9];

Delete the first element of the table using .shift():

var array =  [1, 3, 6, 9];
array.shift(); // [3, 6, 9];

Recovering the size of a javascript table.

The classic technique for retrieving the size of an array is to use the .length() method:

var array =  [1, 3, 6, 9];
console.log(array.length); // 4

Retrieving specific elements from a javascript table.

Find the element located at index ‘a’ by indicating it as an argument between brackets:

var array =  [1, 3, 6, 9];
console.log(array[1]) ; // 3

Alternative for retrieving the element with index ‘a’ using the .at() method:

var array =  [1, 3, 6, 9];
console.log(array.at(1)) ; // 3

To find the position of an element in the array, use the .indexOf(obj) method:

var array =  [1, 3, 6, 9];
console.log(array.indexOf(6)); // 2

A variant with the last appearance of the element in the table is possible using the .lastIndexOf() function:

var array =  [1, 3, 6, 9];
console.log(array.lastIndexOf(6)); // 2

To retrieve part of an array in an interval, the standard approach is to use the .splice(startIndex, endIndex) method:

var array =  [1, 3, 6, 9];
array.splice(0,2); // [1, 3]

Important: The start index is included, while the end index is excluded.

Find the index of the first element meeting a logical condition using the .findIndex() method:

var array =  [1, 3, 6, 9];
array.findIndex(val => val > 3) // 2

Returns the first element to satisfy a logical condition using the .find() method:

var array =  [1, 3, 6, 9];
array.find(val => val > 3) // 6

Find the smallest element in a javascript array with .sort():

var array =  [1, 3, 6, 9];
console.log(array.sort((a, b) => return a-b)); // 6

Find similar elements in two javascript arrays using the .filter() and .includes() methods:

var array =  [1, 3, 6, 9];
var array2 = [6, 9, 11, 13];
var commonElement = array.filter( el => array2.includes(el));
console.log(commonElement); // [6, 9]

Calculate the sum of the values in a javascript array using .reduce():

var array =  [1, 3, 6, 9];
console.log(array.reduce((a, b) => a + b)); // 19

Retrieve the list of indices from an array using .keys():

var array =  [1, 3, 6, 9];
for( const idx of array.keys()){
	console.log(idx); // 0 1 2 3
}

Validating the presence of elements in a javascript table.

Check that a variable is present in a javascript array using .isArray():

var array =  [1, 3, 6, 9];
console.log(Array.isArray(array); // true

Check the presence of an element in the javascript array using .includes():

var array =  [1, 3, 6, 9];
console.log(array.includes(3)); // true
console.log(array.includes(11)); // false

Check that all the elements of a javascript array validate a logical condition defined with the .every() method:

var array =  [1, 3, 6, 9];
console.log(array.every(e => e < 10)); // true
console.log(array.every(e => e > 10)); // false

Check that there is at least one element in a javascript array that validates a logical condition with .some():

var array =  [1, 3, 6, 9];
console.log(array.some(e => e < 10)); // true
console.log(array.some(e => e > 10)); // false

Find the largest element in a javascript array using the Math library:

var array =  [1, 3, 6, 9];
console.log(Math.max.apply(null, array)); // 9

Find the smallest element in a javascript array using the Math library:

var array =  [1, 3, 6, 9];
console.log(Math.min.apply(null, array)); // 1

Handling javascript arrays.

Transformer un tableau javascript.

Keep only part of the table based on a logical condition using .filter():

var array =  [1, 3, 6, 9];
console.log(array.filter(e => e < 6)); // [1, 3]

Merge two arrays into a single javascript array using the .concat() method:

var array =  [1, 3, 6, 9];
var array2 = [11, 13, 15, 17];
console.log(array.concat(array2); // [1, 3, 6, 9, 11, 13, 15, 17]

Transform an array into a character string with a separator element using .join(element):

var array =  [1, 3, 6, 9];
console.log(array.join(‘or”); // “1 or 3 or 6 or 9”

Retain only a section of an array following an interval defined with the .slice() method:

var array =  [1, 3, 6, 9];
console.log(array.slice(1, 2); // [3]

Convert a javascript array into a string using the .toString() function:

var array =  [1, 3, 6, 9];
console.log(array.toString()); // “1, 3, 6, 9”

Convert one or more elements in an array into several elements in an array using .flat():

var array =  [1, 3, 6, [9, 11, 13]];
console.log(array.flat(1)); // [1, 3, 6, 9, 11, 13]

Alternatively, the conversion also requires a transformation with a function using the .flatMap() method:

var array =  [1, 3, 6, [9, ‘11’, 13]];
console.log(array.flatMap(a => a*2)); // [1, 3, 6, 18, 22, 26]
var array =  [1, 3, 6, 9];
console.log(array.splice(2, 2)); // [1, 3]

Remove elements from the array according to an interval using the .splice(index, howMany) method:

By adding elements as arguments, it is possible to add new entries to the table after deleting them.

var array =  [1, 3, 6, 9];
console.log(array.splice(2, 2, 5, 7)); // [1, 3, 5, 7]

Reverse the position of elements in an array using the .reverse() method:

var array =  [1, 3, 6, 9];
console.log(array.reverse()); // [9, 6, 3, 1]

Modify all the elements by replacing them with a single value using the .fill(element) method:

var array =  [1, 3, 6, 9];
console.log(array.fill(1)); // [1, 1, 1, 1]

Copy elements from a javascript array and add them to a specific position in the array using .copyWithin():

var array =  [1, 3, 6, 9];
console.log(array.copyWithin(1, 0, 2)); // [1, 3, 1, 9]

Construct a new javascript array by using a function to transform the elements of another array using .map():

var array =  [1, 3, 6, 9];
console.log(array.map(a => a*2)); // [2, 6, 12, 18]

Sorting the elements of a javascript table.

Sort the elements of a javascript array in ascending order using the .sort() method:

var array =  [1, 9, 3, 6];
console.log(array.sort()); // [1, 3, 6, 9]

Shuffle the elements of a javascript array at random using the .sort() method:

var array =  [1, 9, 3, 6];
console.log(array.sort((a,b) => 0.5 - Math.random() )); // [9, 1, 6, 3]

Transforming and converting a javascript table.

Convert a javascript array into an object using:

var array =  [1, 9, 3, 6];
var obj = { …array };
console.log(obj); // { 0: 1, 1: 9, 2: 3, 3: 6} 

Browse a table using loops:

Browse an array with its indices and elements using the .entries() method:

var array =  [1, 3, 6, 9];
for(const [index, element] of array.entries()){
	console.log(index, element); // 0 1, 1 3…
}

Browse an array using the .forEach() method:

var array =  [1, 3, 6, 9];
array.forEach(element => console.log(element)); // 1 3 6 9

Alternative way of browsing an array using .values():

var array =  [1, 3, 6, 9];
for(const value of array.values()){
	console.log(value); // 1 3 6 9
}

The Lodash library for advanced processing of javascript tables.

Lodash is a library that provides a number of very useful tools for processing variables in javascript, particularly arrays. The methods offered by Lodash are highly modular and are recommended for projects requiring significant manipulation of arrays.

Loadash can be quickly installed in a project using the npm package installer. The command is: npm i lodash.

The following list does not include all the methods offered by the library. These are just the methods offering additional functionality to that already available natively in vanilla js. Nevertheless, it’s worth mentioning that Lodash offers alternatives to almost all table manipulations native to javascript.

Divide an array into several arrays with a number of elements specified as an argument using the .chunk() method:

var array =  [1, 3, 6, 9];
console.log(_.chunk(array, 2)); // [[1, 3], [6,9]]

Remove erroneous elements (null, undefined, ”, false, NaN) from a javascript array using the _.compact() method:

var array =  [1, undefined, 3, null, 6, ‘’, 9];
console.log(_.compact(array)); // [1, 3, 6, 9]

Delete a number of elements defined as an argument, starting from the beginning of the array using the _.drop() method:

var array =  [1, 3, 6, 9];
console.log(_.drop(array, 2)); // [6, 9]

Alternatively, you can delete elements from the end using the _.dropRight() method:

var array =  [1, 3, 6, 9];
console.log(_.drop(array, 2)); // [1, 3]

Transforms arrays into objects made up of a value and key pair using the _.fromPairs() method:

var array =  [[1: ‘a’], [2, ‘b’], [3, ‘c’], [4, ‘d’]];
console.log(_.fromPairs(array)); // { 1:’a’, 2:’b’, 3:’c’, 4:’d’ }

Delete all the elements of a javascript array with values defined in the _.pull() method:

var array =  [1, 3, 6, 9];
console.log(_.pull(array, 1, 9)); // [3, 6]

The inverse of the _.pull() method deletes elements not included in an array supplied as an argument:

var array =  [1, 3, 6, 9];
console.log(_.pullAll(array, [1, 9])); // [1, 9]

Keep only elements with a single value in a javascript array with _.uniq():

var array =  [1, 3, 3, 6, 9];
console.log(_.sortedUniq(array)); // [1, 3, 6, 9]

Retrieve a random element from a javascript array using _.sample():

var array =  [1, 3, 6, 9];
console.log(_.sample(array)); // 6

Conclusion

The items presented in this list cover many of the operations required to use tables in javascript. There are several different approaches to doing the same thing. Going into detail, some of them are rightly considered to be more recommendable, but in reality this depends above all on the need and development habits. That’s why this article doesn’t go into detail.

If you have any tips or techniques to add to this list, don’t hesitate to share them in the comments section :-).

Photo Maxime Macé

Maxime Macé

Simple passionné de thématiques diverses et variées. J’apprécie enrichir mes connaissances dans les disciplines techniques comme l’informatique, les sciences et l’ingénierie, mais aussi dans les domaines merveilleux de la philosophie, l’art et la littérature.

Prenons contact

Vous souhaitez me contacter suite à la lecture de cet article ? Merci de renseigner votre adresse électronique et je vous recontacterai dans les plus brefs délais.

CV Ingénieur développeur informatique

CV Étudiant PhD Artificial Intelligence

Portfolio Artist designer