This article describes how to perform various functions on arrays and loops using JavaScript.
Requirements
- A JavaScript variable, rule, or QScript.
- You have read JavaScript Fundamentals.
Please note these steps require a Displayr license.
Method
1. Manipulating arrays
There are many ways to update and manipulate JavaScript arrays. Let’s look at the following declared brands variable:
const brands = ["Coca-Cola","Diet Coke","Pepsi","Diet Pepsi"];
Adding and removing
If we want to add "Coke Zero" to our brands array, we can use the push()
function to append it to the end of the array:
brands.push("Coke Zero");
This is effectively the same as specifying the fifth position of the array (index 4 as JavaScript is zero-based):
brands[4] = "Coke Zero";
To add the new item to the start of the array, you would instead use unshift()
.
Remember, if simply using the index number to update elements within an array, it will overwrite any existing element, so make sure you use the correct index value. The below, for example, would replace "Coca-Cola" in our array:
brands[0] = "Coke Zero";
If we want to pull out the first element, we can use splice(start, number)
as follows:
brands.splice(0,1); returns Coca-Cola
Here, we need to specify the starting position (i.e. the first element) and the number of elements we wish to extract.
Sorting
Arrays can be sorted like other data types. In this case, sorting is performed alphabetically in ascending order:
brands.sort(); // returns Coca-Cola,Diet Coke,Diet Pepsi,Pepsi
You can return in descending order by using the reverse()
function instead:
brands.reverse(); // returns Diet Pepsi,Pepsi,Diet Coke,Coca-Cola
Note, that these functions modify the original array, so below both brands
and a
have been sorted:
const a = brands.sort;
If you only want to sort a copy of the array, you should use splice
instead:
const a = brands.splice(0); // this creates a new array with the same objects inside a.sort();
To sort by some other order, you can specify a custom comparison function. Below we will sort the values in x
in descending order:
const x = [2, 1, 3];
x.sort(function (a, b) {
return b - a;
});
The sort order is represented in b - a
, where:
- If the numbers are equal,
b - a
= 0. - If
b
is smaller thana
, a negative number is returned (placingb
aftera
in the sorted array).
To sort values in ascending order we would instead use a - b
.
Concatenating
Sometimes we work with multiple arrays but wish to join them into a single array. This can be achieved via the concat()
function. Let’s say we started with these 2 arrays:
const brands1 = ["Coca-Cola","Diet Coke"];
const brands2 = ["Pepsi","Diet Pepsi"];
To combine them into a single array would involve concatenating brands1 with brands2 as follows:
const brands = brands1.concat(brands2);
2. Converting arrays into strings and vice versa
You can interchange between arrays and strings using a handful of methods.
To string
Going back to our brands array, it is possible to pull all the individual elements out and convert them into a single string using toString()
:
brands.toString(); returns "Coca-Cola,Diet Coke,Pepsi,Diet Pepsi"
An even better function is join(separator)
which lets you specify the separator rather than simply using the default comma character:
brands.join(" + "); returns "Coca-Cola + Diet Coke + Pepsi + Diet Pepsi"
To array
The opposite of this is to have a delimited string and use the split(character)
function to separate each item into a separate array element:
let brand = "Coca-Cola,Diet Coke,Pepsi,Diet Pepsi";
const brands = brand.split(",");
In this example, the comma is used as a separator in brand so it is also included as the split()
argument.
3. Loops
Loops generally go hand in hand with arrays as you often need to create, update or extract elements within arrays via looping. The most common example of a loop is the for…Loop
.
for...loop
Let’s use an example to show how to populate an array. First, we declare the number of iterations (n) and an empty array (arr) using square brackets, and then loop through n=5 times to fill the array with the index number (i) plus one:
let n = 5;
const arr = [];
for (let i = 0; i < n; i++) {
arr[i] = i+1;
}
// returns 1,2,3,4,5
Here, the index iterates by one according to the i++
argument where i starts at 0 and loops through until i = n (i.e. 5). Changing this to i--
would reverse the direction of the loop. Note, arr[i] = i+1
could be interchanged with arr.push(i+1)
.
Here’s another example that returns a string by looping through all the elements within the brands array:
let summary = "";
let n = brands.length;
for (let i = 0; i < n; i++) {
summary += "Brand " + (i+1) + " is " + brands[i] + " <br> ";
}
As summary has already been declared at the start as an empty string, we can add to it by using the += operator. This code returns a summary of each item and its name separated by a line break:
Brand 1 is Coca-Cola
Brand 2 is Diet Coke
Brand 3 is Pepsi
Brand 4 is Diet Pepsi
while...loop
A variation of this loop is the while…Loop
method which would be written like below:
while (i < n) {
summary += "Brand " + (i+1) + " is " + brands[i] + " <br> ";
i++;
}
4. Array functions
JavaScript includes some array functions that parse a custom function. These functions take value, index, and array as their inputs but only the first one is required.
forEach()
The first function is the forEach()
method which can also be used with our previous example. In this case, we have placed the summary result within a function called mySummary which loops through each brand and index:
brands.forEach(mySummary);
function mySummary(brand, i) {
summary += "Brand " + (i+1) + " is " + brand + " <br> ";
}
Here, the mySummary arguments of brand and i are equivalent to value and index (with array not being used). This function can appear either before or after the forEach()
code.
map()
A further useful function is the map()
method which creates a new array without having to use loops. It works by taking an existing array and performing a function on each element within the array.
For example, the below will look for all instances of "Pepsi" in brands and return either a true or false:
const pepsiBrands = brands.map(function (x) { return x.indexOf("Pepsi")>-1});
// returns false,false,true,true
Alternatively, this could be written as follows:
const pepsiBrands = brands.map(myPepsiBrands);
function myPepsiBrands(brand) {
return brand.indexOf("Pepsi")>-1;
}
filter()
A similar function to map()
is filter()
which works much the same way except it pulls out only those elements that meet the function's condition:
const pepsiBrands = brands.filter(function (x) { return x.indexOf("Pepsi")>-1});
// returns Pepsi,Diet Pepsi
See Also
How to Use JavaScript in Displayr
How to Work with Conditional JavaScript Formulas
How to Manipulate Strings Using JavaScript