JavaScript Notes

Day 6

Arrays

An array in JavaScript is not a primitive but rather a built-in object. In general, array stores a collection of items of similar types, but in JavaScript, an array can contain a mix of different data types.

Creation of Array Object

There are two ways to create arrays in JavaScript:

  1. arr = []

    Literal syntax. The elements of the array can be specified inside the square brackets or can be added using array methods.

  2. Array() or new Array()

    Constructor syntax. The elements can be passed to the constructor or added via the array methods.

    💡
    Note: If you pass only one element to the array constructor which is an integer value then an empty array of that size is created.
//literal syntax
const fruits = ['apple', 'banana'];
//constructor syntax
const cars = new Array('BMW', 'Audi');
//empty array of size 5
const emptyArr = new Array(5);

Arrays can contain empty elements as well. These are considered undefined. In the example above, the emptyArr contains 5 undefined elements This is done to fulfill the length requirement.

Properties of Array Object

  1. length

    This property is used to find the size of the array. It is also possible to set the size of the array using this property. It has a value between 1 and 2³²-1 inclusive. To fulfil a higher length than the number of actual elements, the array is filled with empty(undefined) elements. When a length lower than the previous length is specified, the extra elements are removed from the array.

  2. prototype

    This property gives access to the various properties and methods available from the Function and Object classes via inheritance.

Accessing Array Elements

As mentioned before, arrays are objects which contain a collection of key-value pairs with the key being the 0-based index and value being any possible data types. To access the elements of the array one must use the key/index in square brackets. One can also put a string in the square brackets, as long as it is a whole number. See the example below:

let arr = [1,2,3]
arr[1] //2
arr['1'] //2

Methods of Array Object

We take a look at some of the important methods of the array object. These are static methods and can be invoked directly from the Array class.

  1. from(arrayLike, mapfn?)

    Creates a new array instance from the array-like or iterable objects, i.e., objects which have a length property and indexed elements. It can also accept a map function, which is run to transform the array-like objects before being added to the array.

  2. isArray(value)

    Determine if the passed value is an array.

  3. of(...args)

    Creates a new array instance from the variable number of arguments.

Array.from('foo');
//["f", "o", "o"]

Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]

Array.isArray([1, 3, 5]);
// true

Array.isArray('abc');
// false

Array.of('foo', 2, 'bar', true);
// ["foo", 2, "bar", true]

Array.of();
// []

There are more methods available in the array.prototype which can be accessed using the syntax arrayVar.methodName(params).Some of these methods mutate the actual array, i.e., they change the actual values of the elements in the array rather can creating a new copy and returning that. Let us have a look at some of the important array.prototype methods.

  1. at(index)

    Returns the element at the specified index in the array. negative values for index count from the end of the array with the last element being at index of -1.

  2. concat(...args)

    Concat two or more arrays and return a new array object. All the arrays are specified as arguments. Empty arguments mean append an empty array.

  3. join(separator?)

    Creates and returns a new string by concatenating all of the elements in the array separated by commas or a specified separator string.

  4. every(callbackFn)

    Tests if every element in the array passes the test provided by the provided function. Returns a boolean value.

  5. some(callbackFn)

    Tests whether at least one element in the array passes the test implemented by the provided function.

  6. fill(value, start?, end?)

    Change the value of the elements from start(inclusive) to end(exclusive) to the provided value. Default values for start and end are 0 and length - 1. Mutates the original array.

  7. filter(callbackFn)

    Returns a portion of the given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

  8. indexOf(searchElement, fromIndex?)

    Returns the first index at which a given element can be found in the array, or -1 if it is not present. If fromIndex is specified, the search starts from that index.

  9. lastIndexOf(searchElement, fromIndex?)

    Returns the last index at which a given element can be found in the array, or -1 if it is not present. If fromIndex is specified, the search starts from that index.

  10. includes(searchElement, fromIndex?)

    Determines whether an array includes a certain value among its entries or not. Returns true or false.

  11. forEach(callbackFn)

    Executes a provided function once for each array element.

  12. map(callbackFn)

    Creates a new array populated with the results of calling the provided function on every element.

  13. reduce(callbackFn, intialValue?)

    Runs the provided function for each element in the array and provides a single value (reduced) at the end. The provided function has three parameters finalValue, currentValue and index. If the intialValue is specified then on the first call finalValue = initilalValue, currentValue = array[0] and index = 0. Otherwise, finalValue = array[0], currentValue = array[1] and index = 1,i.e., the first element is considered as the initial value.

  14. sort(compareFn?)

    Sorts the elements of the array and returns a reference to the original array. Can accept a compare function whose sign indicates the sort order. The function is called with two parameters, a and b. If a < b then negative, a > b then positive and a=b then equal (0). Mutates the original array.

  15. reverse()

    Reverses the elements of the array and returns the reference to the original array. The first element becomes the last, the last the first and so on. Mutates the original array.

  16. slice(start, end)

    Return a new array containing the elements from start (inclusive) to end (exclusive). Does not mutate the original array.

  17. splice(index, deleteCount, ..newItems)

    Changes the contents of an array by removing or replacing existing elements and/or adding new elements. Mutates the original array.

  18. push(...args)

    Adds the specified elements to the end of an array and returns the length of the array. Mutates the original array.

  19. pop()

    Removes the last element from the array and returns the element. Mutatues the original array.

  20. shift()

    Removes the first element from the array and returns the element. Mutates the original array.

  21. unshift(..args)

    Adds the new elements to the start of the array and returns the new length. Mutates the original array.

  22. toString()

    Returns a string representing the string representation of the array and its elements.

The below code shows examples of the methods listed above.

const array1 = [5, 12, 8, 130, 44];
array1.at(2)
// 8
array1.at(-2)
// 130
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
// [5,12,8,130,44,'d','e','f']
const isBelowThreshold = (currentValue) => currentValue < 40;
array1.every(isBelowThreshold)
// false
array1.some(isBelowThreshold)
// true
const array4 = [1,2,3,4];
array4.fill(0, 2, 4);
// [1, 2, 0, 0]
const arrString = array4.join("-");
// "1-2-0-0"
array4.indexOf(0);
// 2
array4.lastIndexOf(0);
// 3
array2.includes('m');
// false
const array5 = array4.map((item) => item + 1);
// [2,3,4,5]
const array6 = array5.filter((item) => item < 4);
// [2,3]
const sum = array6.reduce((total, item) => total+=item, 0);
// 5
array6.push(5);
// [2,3,5]
array6.pop();
// [2,3]
array6.shift();
// [3]
array6.unshift(1,2);
// [1,2,3]
const aString = array6.toString()
// "1,2,3"
array6.reverse();
// [3,2,1]
array6.forEach((item) => {console.log(item});
/*
3
2
1
*/
arrays6.sort();
// [1,2,3]
const array7 = [1,2,3,4,5,6];
const array8 = array7.slice(2,4);
// [3,4]
array7.splice(1,2);
// [1,4,5,6]

By utilizing these methods, developers can efficiently manipulate arrays in JavaScript. For further understanding and more methods, visit the MDN documentation.