Arrays
Intro
- This tutorial covers JavaScript Arrays.
- It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar.
- The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.
1. What are arrays
- JavaScript arrays are list-like objects. They store multiple values, called elements, in a single variable.
- You can create an array literal using the array operator, a pair of square brackets [].
- Each element has an associated index number that is its order in the array. Array indexes are 0 based so the first element is at index 0, the second is at index 1, etc.
- You can think of arrays as objects whose keys are the index numbers 0, 1, 2, 3 etc.
- Arrays can change length and the elements can be of one or more data types.
- Arrays are not their own data type, rather they are a type of object.
const arr = ['apple', 'banana', 'orange'];
let view = typeof arr; // returns 'object'
- In general, arrays should be assigned to const variables unless you plan to assign that variable name to another array or other value. Since arrays are objects they are saved by reference not value. So if you add, remove, or modify array elements it does not change the array reference value.
Array global object
- As with many other JavaScript constructs, Arrays have a standard built-in object on the global scope called Array.
Object.getPrototypeOf([]) === Array.prototype; // returns true
- The Array global object includes:
- Array(): A constructor function to instantiate new array objects.
- Array: Static properties and methods you access or call on the Array global object.
- Array.prototype: The prototype property is an object that holds instance properties and methods you can call on array instances.
2. Create an array
- There are a few different ways to create an array. The preferred way is to create an array literal. Place the elements inside square brackets separated by commas.
const arr = ['apple', 'banana', 'orange'];
- You can also call the array constructor function with the new operator. new is part of an object creation expression. Pass in the array elements as arguments.
const arr2 = new Array('cherry', 'watermelon', 'peach');
- Or call it as a regular function without the new keyword. Both ways will create a new array object.
const arr3 = Array('mango', 'tangerine', 'pomegranate');
- The Array.of static method will also create a new Array. Just pass in the elements as arguments.
const arr4 = Array.of('strawberry', 'blueberry', 'rasberry');
3. Get and Set Array Elements
- You can get an array element's value with its index number. Place the index number in square brackets and append it to the array.
const arr = ['apple', 'banana', 'orange'];
let view = arr[0]; // returns 'apple'
- To get the last element's index number, subtract one from the length property.
view = arr[arr.length - 1] // returns 'orange'
- You can change an element value using the equals sign.
arr[1] = 'blackberry';
view = arr[1]; // returns 'blackberry'
4. Array Static methods
- Static methods are functions that are attached to a class or constructor function. You chain them directly to the Array constructor function. Instance methods on the other hand are chained to specific array objects.
- The full list of Array static properties and methods is:
Object.getOwnPropertyNames(Array); // returns length, name, prototype, isArray, from, of
Array.of()
- We already looked at the Array of method for creating new arrays.
const arr = Array.of('apple', 'orange', 'banana');
Array.from()
- Array.from creates a shallow copy of an array. We will cover Array.from in the shallow copy section.
Array.isArray()
- Since array is not a datatype, to test if a value is an array you can use the Array.isArray static method, passing in the value as the argument. It returns true if it is an array, false otherwise.
let view = Array.isArray(arr); // returns true
5. Array Instance properties
- Like all constructor functions, Array has a prototype property that holds all the instance properties and methods that can be applied to array instances.
- The full list of Array instance properties and methods is:
Object.getOwnPropertyNames(Array.prototype); // Returns: length, constructor, concat, copyWithin, fill, find, findIndex, lastIndexOf, pop, push, reverse, shift, unshift, slice, sort, splice, includes, indexOf, join, keys, entries, values, forEach, filter, flat, flatMap, map, every, some, reduce, reduceRight, toLocaleString, toString, at, findLast, findLastIndex
constructor
- The constructor property is a reference to the Array constructor function:
const arr = ['apple', 'banana', 'orange']; let view = arr.constructor; // returns Array
length
- The length property returns the number of elements in an array.
view = arr.length; // returns 3
- You can also set the length of an array. It will populate the array with undefined for each element that isn't already in the array. Or it will remove elements if they exceed the number you set.
arr.length = 5; // arr is now ['apple', 'banana', 'orange',,,]
arr.length = 2; // arr is now ['apple', 'banana']
6. Instance methods
Modify the array
- Instance methods are functions applied to an instance of a class or prototype. In this case to array instances.
- We saw in the last section that Array.prototype has quite a few of them.
- To execute the method, chain it to the array instance:
arr.method()
- We will start with mutator methods. Mutator methods modify the underlying array and return some result.
6a. Add/remove elements at start/end of array.
- First let's look at the methods that add or remove elements at the start or end of the array.
Array.prototype.shift()
- Below is an array with three string elements "a", "b", and "c".
- The shift method removes an element from the beginning of the array and returns it.
const arr = ['a', 'b', 'c'];
let elem = arr.shift(); // arr is now ['b', 'c'] elem; // returns 'a'
Array.prototype.unshift()
- The unshift method adds an element to the beginning of an array. The below method adds the number 1 to the beginning of the array.
arr.unshift(1); // arr is now [1, 'b', 'c']
Array.prototype.pop()
- The pop method removes the last element in the array and returns it. The below method removes the last element 'c' from the array.
let elem = arr.pop(); // arr is now [1, 'b'] elem; // returns 'c'
Array.prototype.push()
- The push method adds an element to the end of the array. The below method pushes the number 3 to the end of the array.
arr.push(3); // arr is now [1, 'b', 3']
6b. Add/change/remove elements in middle of array:
- Now let's look at methods that add, change, or remove elements from the middle of the array.
- We already saw how to set an element's value using bracket notation with index number .
- In the below example we set the element's value at index 2, changing it from lowercase "c" to uppercase "C".
let arr = ['a', 'b', 'c', 'd', 'e'];
arr[2] = 'C'; // arr is now ['a', 'b', 'C', 'd', 'e']
- If you know the value but not the index number of an element you want to change or delete, you can find it with the indexOf method.
- In the below example we want to change the element 'd' to 'D'. Start by getting the index of value 'd', which is index 3, and set it to variable i.
- Then place the index variable i in the square brackets and set the value to capital "D".
// Find index of element 'd', then change it to 'D'
let i = arr.indexOf('d'); // i is set to index 3
arr[i] = 'D'; // arr is now ['a', 'b', 'C', 'D', 'e']
Array.prototype.splice()
- The splice method can be used to remove a single element from the middle of the array.
- Chain it to the array with two arguments. The index number and the number of elements to remove, which in this case is 1. In the below example we remove the element at index 3.
arr = ['a', 'b', 'c', 'd', 'e']; arr.splice(3, 1); // arr is now ['a','b','c','e'];
- The return value of the splice method is an array holding the removed element. In the above example we didn't do anything with the return value. If you want to capture the removed value then set set the result to a variable.
arr = ['a', 'b', 'c', 'd', 'e']; let arr2 = arr.splice(3, 1); // arr is now ['a','b','c','e']; arr2; // returns ['d'];
- If you don't have a second argument of how many elements to remove, it will remove all the remaining elements. Below we remove all elements from index 3 onward and set the return value to arr2.
arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.splice(3); // arr is now ['a','b','c']; arr2; // returns ['d','e'];
- If you use a negative number as the argument, it will count backwards from the end of the array. Splice -2 will remove that last two elements from the array.
arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.splice(-2); // arr is now ['a','b','c'];
arr2; // returns ['d','e'];
- After you remove one or more elements you can insert new ones in their place by adding them as additional arguments to the splice method.
- In the below example, starting at index 1, we remove 2 elements, and insert two elements in their place: capital 'B' and capital 'C'.
arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.splice(1, 2, 'B', 'C'); // arr is now ['a','B','C','d','e']; arr2; // returns ['b','c'];
- In the next example starting at index 1, we remove 3 elements, and in their place insert one new element: capital 'C'.
arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.splice(1, 3, 'C'); // arr is now ['a','C','e'];
arr2; // returns ['b','c','d'];
- Next at index 2 we remove one element and insert 3 new elements in its place: "c1", "c2" and "c3".
arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.splice(2, 1, 'c1', 'c2', 'c3'); // arr is now ['a','b','c1,'c2','c3','d','e'];
arr2; // returns ['c'];
- You can also use splice to insert multiple elements in the middle of the array without removing any.
- Start with the index where you want to insert the new elements. This is the insertion point. For the second argument, the number of elements to remove is 0. The rest of the arguments are the elements you want to insert.
- In the below example, at index 3 we remove 0 elements, and insert one new element: "c2".
arr = ['a', 'b', 'c', 'd', 'e'];
arr.splice(3, 0, 'c2'); // arr is now ['a','b','c','c2','d','e']
6c. Array of objects: add, update, and remove elements
- So far we have been working with arrays of primitive string and number values. You can also work with arrays of objects. In this section we will cover how to add, update, and remove objects from an array.
Array.prototype.findIndex()
- Below is an array of three user objects.
- You cannot use indexOf to find an element by an object property, like by user id. Instead use findIndex which takes a callback function as the argument. In the callback, pass in the element and search each object by its id property until you find a match with user id 1. We assign the result to the variable i.
const users = [{ id: 1, name: 'Joey' }, { id: 2, name: 'Sheena' }, { id: 3, name: 'Johnny' }];
const i = users.findIndex((user) => user.id === 1); // returns index 0
Add an object to an array:
- To add a user object to the users array first create the object.
- Then add it to the array the usual way. The push method will add it to the end of the array.
const user4 = { id: 4, name: 'Judy' };
users.push(user4); // user4 is now added to the array.
Modify an object property in an array:
- To change a property value:
- Apply bracket notation to the array with the element's index number:
users[0]
- Chain the property name you want to change:
.name
- And assign a new value to it:
= 'Joseph'
users[0].name = 'Joseph';
users[0]; // returns { id: 1, name: 'Joseph' }
Remove object element from array:
- You remove object elements from the array the same way you do other types of elements. Use the splice method, passing in the index number. We will pass in the index variable i, which we set earlier to index 0. Follow that with the number of elements to remove, which is 1.
i; // returns 0 users.splice(i, 1); // removes the user object at index 0 from the array
6d. Sort
Array.prototype.sort()
Default compare function:
Sort strings:
Sort numbers:
Sort case insensitive:
- The sort method sorts array elements in place, changing the underlying array, and returns the modified array.
Default compare function:
- The default compare function sorts any undefined elements to the end of the array. All other elements are converted to strings and compared by UTF-16 code unit order.
- UTF-16 code units sort in the following order:
- Numbers 0-9 come first.
- Then upper case letters A-Z
- Then lower case letters a-z.
- All elements are sorted by their first character in ascending order. Ties are sorted by the second character. Further ties are sorted by the third character, and so on.
Sort strings:
- Below is a straight forward example that sorts the string elements in the array in alphabetical order. It uses the default compare function.
let arr = ['cat', 'eel', 'ant', 'bee', 'dog'];
arr.sort(); // arr is now ['ant', 'bee', 'cat', 'dog', 'eel']
- The below array includes both numbers and lower and uppercase letters. Since it uses the default compare function:
- Numbers are converted to string digit characters. It looks only at the first character so the digit 1 comes before the digit 9.
- After numbers come uppercase letters including "B".
- After uppercase letters come lowercase letters "a" and "c".
arr = ['ant', 'Bird', 'cat', 9, 10];
arr.sort(); // arr is now [10, 9, 'Bird', 'ant', 'cat']
- To sort numbers use the compare function
(a,b) => a ± b
. (a, b) => a - b
sorts numbers in ascending order:
arr = [7, -3, 21, 0];
arr.sort((a, b) => a - b); // arr is now [-3, 0, 7, 21]
(a, b) => b - a
sorts numbers in descending order:
arr = [7, -3, 21, 0];
arr.sort((a, b) => b - a); // arr is now [21, 7, 0, -3]
- To read how the compare function works see: MDN_Array/sort
Sort case insensitive:
- To sort an array of strings case insensitive use the localeCompare function and pass in the option { sensitivity: 'base' }
- The below example sorts in ascending order.
arr = ['cat', 'Eel', 'ant', 'Bee', 'dog'];
arr.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' })); // arr is now ['ant', 'Bee', 'cat', 'dog', 'Eel']
- To sort in descending order switch a and b in the callback function.
arr = ['cat', 'Eel', 'ant', 'Bee', 'dog'];
arr.sort((a, b) => b.localeCompare(a, 'en', { sensitivity: 'base' })); // arr is now ['Eel', 'dog', 'cat', 'Bee', 'ant']
- To sort objects, use the compare function and chain the property you want to sort by to the a and b parameters.
- The below example sorts an array of users by the age property which is a number.
const users = [{ name: 'Joey', age: 31 }, { name: 'Sheena', age: 22 }, { name: 'DeeDee', age: 19 }];
users.sort((a, b) => a.age - b.age);
- The next example sorts the users array by the name property which is a string. We are searching case sensitive so uppercase letters will come before lowercase letters.
users.sort((a, b) => a.name - b.name);
- To sort them case insensitive, use the localeCompare function with the sensitivity option set to base.
users.sort((a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }));
6e. Other mutator methods
Array.prototype.reverse()
- The reverse method reverses the order of the array elements.
let arr = ['a', 'b', 'c'];
arr.reverse(); // arr is now ['c','b','a']
Array.prototype.fill()
- The fill method takes a value as the first argument, and fills the existing elements of the array with that value.
- The below example is an array with 5 string elements. We chain the fill method to it with a dash character, so it fills all 5 elements with the dash value.
arr = ['a', 'b', 'c', 'd', 'e'];
arr.fill('-'); // arr is now ["-", "-", "-", "-", "-"];
- The fill method takes an optional second argument for the starting index number. The below example has a second argument of 2, so the dashes aren't filled in until index 2.
arr = ['a', 'b', 'c', 'd', 'e'];
arr.fill('-', 2); // ["a", "b", "-", "-", "-"];
- Fill takes an option third argument for the end index. The below example has a third argument of 3, so the dashes are filled in starting from index 1 and ending before index 3.
arr = ['a', 'b', 'c', 'd', 'e'];
arr.fill('-', 1, 3); // ["a", "-", "-", "d", "e"];
7. Accessor Methods
- Accessor methods return a representation of the array but do not change the underlying array.
Array.prototype.slice()
- The slice method is similar to the splice method. It returns a copy of the whole array, or part of the array if you include a start and end index as arguments. The difference is, with splice you actually remove those elements from the underlying array. With slice the underlying array does not change.
- Below is an array of 5 string elements, "a" through "e", assigned to variable arr.
- The slice method return an array with a copy of elements starting at index 1 and ending just before index 3.
- The original array, arr, does not change. But arr2 now contains an array with the two copied string elements "b" and "c".
let arr = ['a', 'b', 'c', 'd', 'e'];
let arr2 = arr.slice(1, 3); arr; // returns ['a', 'b', 'c', 'd', 'e']; arr2; // returns ['b','c']
- Leaving out the second argument will slice from the first argument index to the end of the array. The below example applies the slice starting at index 2 with no second argument, so it goes to the end. It returns an array with elements "c", "d" and "e", and no changes to arr.
arr2 = arr.slice(2); // sets arr2 to ['c','d','e']
- Using a negative number, -2, for the argument slices elements starting 2 from the end. The below example returns an array containing "d", "e".
arr2 = arr.slice(-2); // sets arr2 to ['d','e']
- If you don't include any arguments it returns an array with a copy of all the elements: "a" through "e".
arr2 = arr.slice(); // sets arr2 to ['a','b','c','d','e']
- We will do one last slice example. Below we use the indexOf method to find the index of element "c", which is 2, and assign it to variable i.
- Then we use i as the argument to slice, so it returns an array with elements starting at index 2, which are "c", "d", "e".
const i = arr.indexOf('c'); // 2
arr2 = arr.slice(i); // sets arr2 to ['c','d','e']
Array.prototype.concat()
- The concat method joins elements or other arrays to an array. It returns the new array without changing the original.
- The below example chains the concat method to array arr and passes in two strings: 'F' and 'G'. It assigns the result to arr2.
- Arr remains unchanged, but arr2 now contains an array with elements "a" through "G".
arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.concat('F', 'G');
arr2; // returns ['a','b','c','d','e','F','G']
Array.prototype.toString()
- The toString method returns the array as one string, with the elements separated by commas.
arr2 = arr.toString(); // returns "a,b,c,d,e"
Array.prototype.join()
- The join method also returns the array as one string, but it has an optional separator argument that lets you add a custom separator between elements. Below are several examples using different separators. If there is no argument is uses commas as separators. To have no separator, pass in an empty string as the argument.
arr2 = arr.join(); // returns "a,b,c,d,e"
arr2 = arr.join(', '); // returns "a, b, c, d, e"
arr2 = arr.join('-'); // returns "a-b-c-d-e"
arr2 = arr.join(' '); // returns "a b c d e"
arr2 = arr.join(''); // returns "abcde"
8. Search methods
- There are a number of methods that let you search for elements in an array.
Array.prototype.indexOf()
- We've already been using the indexOf method. Add a searchElement as the argument and it will search the array for it. It returns the index number of the first match, or minus 1 if there are no matches.
const names = ['Joey', 'Sheena', 'Johnny', 'Joey', 'DeeDee'];
let view = names.indexOf('Joey'); // Returns 0
Array.prototype.lastIndexOf()
- LastIndexOf does the same thing as indexOf but it starts the search from the end of the array. So it returns the last match in the array.
view = names.lastIndexOf('Joey'); // Returns 3
Array.prototype.findIndex()
- The findIndex method is like indexOf in that it returns the index number of the first match it finds, or returns minus 1 if there are no matches. The difference is instead of taking the value as its argument, it takes a callback function. That allows you to do customized searches.
- The below findIndex method cycles through the array. The callback function passes in each array value and tests it agains a criteria in the function body. The criteria tests if the element is greater than or equal to 21.
const ages = [20, 16, 19, 24, 26, 19];
view = ages.findIndex((age) => age >= 21); // returns 3
- The next search methods return true or false.
Array.prototype.includes()
- Includes returns true if there are any elements in the array that match the searchElement argument. Returns false if not.
view = ages.includes(26); // returns true
Array.prototype.some()
- Some also returns true if there are any elements in the array that match the searchElement argument and false if not. It differs from includes in that it takes a callback as the argument so you can customize the search criteria.
view = ages.some((age) => age >= 21); // returns true
Array.prototype.every()
- Every also takes a callback as the argument, but it returns true only if all elements match the criteria. The below example checks if every element in the ages array is a number.
view = ages.every((elem) => typeof elem === 'number'); // returns true
- There are a couple methods that return the actual matched elements instead of an index number or boolean.
Array.prototype.find()
- The find method takes a callback function as the argument and returns the first element that matches the criteria.
view = ages.find((age) => age >= 21); // returns 24
- The below example uses find to search an array of objects for the first object with an age property that is greater than or equal to 21.
const users = [{ name: 'Joey', age: 18 }, { name: 'Sheena', age: 27 }, { name: 'Johnny', age: 26 }];
view = users.find((user) => user.age >= 21); // returns {name: 'Sheena', age: 27}
Array.prototype.filter()
- The filter method also takes a callback function as the argument but returns every element that matches the search criteria and puts them in an array. Below is an example of the filter method in an array of numbers.
view = ages.filter((age) => age >= 21); // returns [24, 26]
- The below example filters an array of objects.
view = users.filter((user) => user.age >= 21); // [{name: 'Sheena', age: 27}, {name: 'Johnny', age: 26}]
9. Iteration Methods
- Iteration methods iterate through the entire array and perform some operation on each element.
Array.prototype.forEach()
- The forEach method of one of the most commonly used array methods. It essentially does the same thing as a for...of loop. It takes a callback function as the argument and executes it on each element in the array that it iterates through. It returns undefined.
- The example below iterates through an array and logs each element to the console.
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.forEach((elem) => {
console.log(elem);
});
- The first argument to the callback is the array element value.
- The second optional argument is the index number of the element. The below example logs the index and value to the console.
arr.forEach((elem, i) => {
console.log(`${i}: ${elem}`);
});
- In the next example we want to put all the array elements into a string separated by commas, but we want to separate the last two elements with the word "and".
- To accomplish this we create an empty string variable named str.
- Then in the forEach callback function we use the addition assignment shortcut operator += to add each element to the end of the str variable.
- On each iteration we check if the index i is less than the length of the array minus 1. If not then it is the last element so we add the word "and" before it and end with a period.
- When the iterator is done it logs the string to the console.
let str = '';
arr.forEach((elem, i) => {
if (i < arr.length - 1) {
str += `${elem}, `;
} else {
str += `and ${elem}.`;
}
});
console.log(str); // logs a, b, c, d, and e.
Array.prototype.map()
- The map method performs an operation on each element in the array and returns a new array with those changes. The original array does not change.
- The below example uses the map method to create a new array with all the elements in upper case and assigns it to the arr2 variable.
const arr = ['a', 'b', 'c', 'd', 'e'];
arr2 = arr.map((item) => item.toUpperCase());
arr2; // returns ['A','B','C','D','E']
- You can optionally include the index number as the second argument. The below example changes the element to upper case if the index is greater than 0.
arr2 = arr.map((item, i) => {
if (i > 0) return item.toUpperCase();
return item;
});
arr2; // returns ['a','B','C','D','E']
- If you want to use the map method to change the original array, just assign the result back to the arr variable.
arr = arr.map((item) => item.toUpperCase());
arr; // returns ['A','B','C','D','E']
Array.prototype.reduce() and reduceRight()
- The reduce method executes a callback function, called the reducer, on each member of the array resulting in a single output value.
- The reduceRight method does the same thing except it starts from the end of the array and goes to the beginning.
- The below example has an array of numbers 1 through 5.
- We want to add the elements together.
arr = [1, 2, 3, 4, 5];
const res = arr.reduce((accum, num) => accum + num);
res; // returns 15
- The reduce method above iterates through the array passing in one element for each iteration.
- In the callback function the first argument accum is the return value from the previous iteration. The second argument num is the current element passed in for that iteration.
- The function body on each iteration simply adds the two parameter values together, so each element gets added to the accumulated total. When the method finishes iterating through the array it returns the final accumulated total: 15.
10. Shallow copy
- Variables assigned to primitive values like strings, numbers, and booleans store the value directly. Arrays, which are a type of object, are stored in heap memory. Variables assigned to arrays store the address to the array in memory, not the array itself.
- Shallow copying an array creates a new array in heap memory and copies the element values from the original array into the new array.
- There are a few ways to shallow copy an array.
Spread operator:
- You can use the spread operator, which is three dots followed by the array, placing it in array literal square brackets.
const arr = ['a', 'b', 'c'];
let arr2 = [...arr]; arr2; // returns ['a','b','c']
- The two arrays now hold identical elements, but they are not equal. The variables store different memory addresses.
let view = (arr === arr2); // returns false.
Slice method:
- The slice method with no arguments will also return a shallow copy of an array.
arr2 = arr.slice();
arr2 // returns ['a','b','c']
Array.from():
- The Array.from static method, passing in the array as the argument also returns a shallow copy of the array.
arr2 = Array.from(arr);
arr2; // returns ['a','b','c']
Modified shallow copies:
- You can shallow copy an array and add, update, or remove elements in the copy.
- The example below shallow copies an array with the spread operator in an array literal. It adds element 'd' by placing a comma followed by the additional element.
arr2 = [...arr, 'd'];
arr2; // returns ['a', 'b', 'c', 'd'];
- The map and filter methods we have already covered create a modified copy of an array.
// copy arr, changing "c" to "X" arr2 = arr.map((elem) => ((elem === 'c') ? 'X' : elem));
arr2; // returns ['a', 'b', 'X'];
// copy arr, removing "b"
arr2 = arr.filter((item) => item !== 'b');
arr2; // returns ['a', 'c'];
11. Array-like Objects including Sets
- Array-like objects are not arrays but have some array-like qualities such as having a length and having indexed properties. You cannot use the Array instance methods on them but you can use the for...of loop to iterate over them.
- Examples of array-like objects include strings, the function arguments object, sets, and HTMLCollections.
String as an array-like object
- Below is a string variable called str.
- Strings have some array-like characteristics.
- The length property returns the number of characters in the string.
- You can access specific character values by their index numbers.
- But applying the isArray static method to a string confirms that is is not an array.
const str = 'hello';
let view = str.length; // returns 5
view = str[0]; // returns 'h' view = Array.isArray(str); // returns false
- Array-like objects can be converted to an array using the spread operator inside square brackets or by using the Array.from method:
let strArr = [...str]; // returns ['h','e','l','l','o']
strArr = Array.from(str); // returns ['h','e','l','l','o']
Function arguments object as an array-like object
- JavaScript automatically converts function arguments into an array-like object when the function is called.
- In the example below the myFunc function has three parameters. When the function is called, the arguments passed in automatically become properties of the arguments object. Like with arrays:
- We can apply the length property to it. It returns 3 for 3 arguments.
- Arguments are indexed so arguments[0] returns the value 'a'.
- But the Array.isArray() method shows that arguments is not an array.
- The spread operator in square brackets converts it to an array.
function myFunc(param1, param2, param3) {
view = arguments; // returns the Arguments object
view = arguments.length; // returns 3
view = arguments[0]; // returns 'a'
view = Array.isArray(arguments); // returns false
const argsArr = [...arguments]; // returns ['a','b','c']
}
myFunc('a', 'b', 'c');
Set
- Set is a global object sibling of Array. It was added to JavaScript as part of ES6 released in 2015. Set creates an object out of an array and eliminates duplicates if there are any.
- The below example instantiates a set object called mySet by calling new Set and passing in an array to create the set from. The duplicate elements 'a' and 'd' are automatically removed.
- It uses a size property in place of length and returns 4.
- Array.isArray returns false.
- But you can convert it to an array using the spread operator or Array.from.
const mySet = new Set(['a', 'a', 'c', 'd', 'e', 'd']); // Remove dups. view = mySet.size; // returns 4 view = Array.isArray(mySet); // returns false const setArr = [...mySet]; // returns ['a','c','d','e']
- And that concludes this tutorial on JavaScript arrays.
Conclusion
The topics in this tutorial correspond with the JavaScript CheatSheet Arrays category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.