Javascript  

 

 

 

 

 

Array

 

This note is not much of programming... it would be just about basic syntax. The syntax about handling Array in Javascript.

 

  • push() and pop(): These methods add and remove elements from the end of an array, respectively.
  • shift() and unshift(): These methods add and remove elements from the beginning of an array, respectively.
  • splice(): This method can be used to add or remove elements from anywhere in an array.
  • slice(): This method returns a new array that contains a subset of the elements of the original array.
  • concat(): This method can be used to combine two or more arrays into a single array.
  • indexOf(): This method returns the index of the first occurrence of a specified element in an array, or -1 if the element is not present.
  • join(): This method can be used to join all elements of an array into a single string.
  • sort(): This method can be used to sort the elements of an array in ascending or descending order.
  • reverse(): This method can be used to reverse the order of the elements in an array.
  • map(): this method is used to create a new array with the same length as the original array, but with the elements transformed according to the provided function.
  • Apply Function : Apply a function (e.g, a Math function) to every element of an array
  • Spread Opeartor : Spread an array to a sequence of individual elements

push / pop

This is how you can define/create an array

 

The push method is used to add an element to the end of the array:

 

The pop method removes the last element from an array and returns that element. In this case, the method returned 1, indicating that 1 was the last element in the array a before pop was called

shift/unshift

An array is created as follows.

 

The shift method removes the first element from an array and returns that element. The output 4 indicates that 4 was the first element in the array a before shift was called.

 

The unshift method adds one or more elements to the beginning of the array and returns the new length of the array. In this example, The unshift method is called with the argument 10 and you see the number 10 is added at the beginning of the array.

slice

The slice method is used to return a shallow copy of a portion of an array into a new array object, selected from start to end (end not included). The output shows the result of this slice

In the first example, the slice method is called with the arguments (0,1). It has sliced the array from index 0 up to, but not including, index 1, which results in an array containing just the first element [10].

In the second example, the slice method is called again with the arguments (2,5). This slices the array from index 2 up to, but not including, index 5, resulting in [8, 2, 7]

splice

The splice method changes the contents of the array by removing existing elements and/or adding new elements. The splice method is a versatile array method that can both remove and add elements within an array, modifying the array in place

In this example, it's removing two elements starting from index 1. The console output shows the elements that were removed from the array, which are [5, 8]. After the splice operation, the original second and third elements (5 and 8) are now removed, leaving the updated array with the remaining elements.

 

In this example, the statement a.splice(1,2,10,9) performs the following operations on the array a:

  • It starts at index 1 of array a.
  • Removes 2 elements from the array starting at that index.
  • Inserts the numbers 10 and 9 at that same index.

 

In this example, the splice method is invoked with the parameters (-1,1). This indicates that the splice method should remove 1 element starting from the end of the array (as -1 signifies the last index of the array).The result of the splice operation is [8]. This is the element removed from the array, which is the last element (8) due to the -1 index. The array a after the splice operation is: [10, 5, 8, 2, 7]

 

In this example, the splice method is called on array a with the parameters (-1,1,8). This command starts at the last element of the array (due to the -1 index), removes one element (1), and then adds 8 at that position. The result of the splice method is [7], which means that 7 was the element removed from the array. The final state of the array a after the splice operation is shown as:[10, 5, 8, 2, 8]. This indicates that the last element (7) was successfully replaced with 8.

indexOf

The indexOf method is used to search an array for a specified element and returns its index. If the element is found, indexOf returns the index of the first occurrence of the value. If the element is not found, it returns -1.

In this example:

  • a.indexOf(8) returns 2 because the first occurrence of the element 8 is at index 2 in the array a.
  • a.indexOf(20) returns -1 because the element 20 is not found in the array a.

concat

The concat method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.

The concat method does not alter the original arrays. To update array a with the new concatenated array, the result of a.concat(b) needs to be assigned back to a as shown in this example.

join

The join method is used to join all elements of an array into a string. By default, join uses a comma to separate each array element. If you pass a string to the join method, it will use that string as a separator instead of a comma.

 

In this example, an array s is created with two string elements: s = ['Hello', 'World'].  The join method is then called on array s without any arguments, which will use the default comma separator resulting in 'Hello,World'.

If s.join() is provided with an argument, such as s.join(' '), it would join the elements with a space instead, resulting in 'Hello World'.

sort

Array.prototype.sort() method, which sorts the elements of an array in place and returns the sorted array.

When the sort method is called without a compare function, it converts the elements into strings and compares their sequences of UTF-16 code units values.

In this example, a compare function is provided to the sort method, which defines the sort order. If the compare function returns a value less than 0, it will sort a to a lower index than b, i.e., a will come first.

 

In this example, The arrow function (a, b) => a - b dictates how the elements should be sorted: If the result of a - b is negative, a is sorted before b. If it's positive, b is sorted before a. After the sort operation, the array a is now sorted in ascending order:

 

In this example, the sort method is called with a compare function that uses localeCompare. The localeCompare method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Here, b.localeCompare(a) sorts the array in reverse alphabetical order considering localization. After the sort operation, the array s is sorted in reverse alphabetical order:

 

In this example, the arrow function (a, b) => b.localeCompare(a) is passed to the sort method as the compare function. The localeCompare method is used to determine the sort order based on the local language settings, which is useful for sorting strings that contain non-ASCII characters. The comparison is done in reverse order because b is compared to a instead of the more typical a to b. As a result, the array is sorted in descending order considering localization.

map

The map() method creates a new array by calling a provided function on every element in the calling array. It applies the function individually to each of the array's elements in order. The original array remains unchanged; map() returns a new array containing the results.

In this example, the map method is called on array a with a function that squares each element (x) of the array. The map method creates a new array with the results of calling the provided function on every element in the calling array.

After the map operation, the original array a is still same as original because map does not modify the original array but instead returns a new array.

 

This example does exactly same as above. The only difference is that I used arrow function.

Apply Function

This example is to show an example of using the Math.max function with an array in JavaScript, not the map method. The Math.max function returns the largest of zero or more numbers, but it does not work directly with arrays. The spread operator (...) is used to spread the array elements as individual arguments to the function.

In this example, an attempt is made to find the maximum value in the array using Math.max directly on the array, which results in NaN because Math.max expects a list of numbers, not an array.

The correct way to find the maximum value in the array using Math.max is then demonstrated using the spread operator to pass the elements as individual arguments:

Spread Operator

spread operator allows an iterable such as an array to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

'...a' expands the original array a, and the new elements 1, 20, and 21 are added at the beginning and the end of the array, respectively. The resulting array a will include the spread elements from the original array along with the new elements.

 

In this example, arr1 is being copied to create a new array arr2, and an element is being inserted into arr2 at the first index. This example uses the spread operator to slice arr1 and insert element into the resulting array to create arr2.

Object Array

An object array is an array that contains elements that are objects. Each element in the array is an object, and each object has its own properties and methods.

 

An object can be defined as an instance which contains set of key-value pairs and it can be defined using the object literal notation {} or the object constructor notation (new Object()).

 

This example is meant to demonstrate how to create a collection of objects that could represent, for example, coordinates with associated colors on a 2D plane.

  • An empty array a is declared.
  • An object with properties x, y, and color is pushed into the array a. This object has x set to 1.2, y set to 3.2, and color set to 'red'.
  • The array a is logged to the console, showing it now contains one object.
  • A second object with x set to 2.2, y set to 3.2, and color set to 'blue' is pushed into the array a.
  • The array a is logged again, showing it now contains two objects.
  • A third object with x set to 3.2, y set to 1.2, and color set to 'black' is pushed into the array a.
  • The final state of the array a is logged, showing it contains three objects, each with distinct x and y coordinates and colors.

 

This code snippet shows how to initialize an array and add multiple objects to it in one operation, with each object representing a point with a color on a 2D plane.

An empty array a is declared.

  • The .push() method is used to add three objects at once to the array a. This is done by passing all three objects, separated by commas, within the .push() parentheses.
  • After the push operation, the console logs the number 3, which is the new length of the array a after the three objects are added.
  • Finally, the array a is printed out, showing that it now contains three objects with properties x, y, and color. Each object has different values for these properties.

 

The code snippet demonstrates declaring individual objects and then sequentially adding them to an array, showcasing basic array manipulation and object handling.

  • An empty array a is initialized.
  • Three separate objects o1, o2, and o3 are created, each with x, y, and color properties. They represent points with different colors.
    • o1 has x: 1.2, y: 3.2, color: 'red'
    • o2 has x: 2.2, y: 3.2, color: 'blue'
    • o3 has x: 3.2, y: 1.2, color: 'black'
  • Each object is then added to the array a using the .push() method.
    • .push(o1) adds the first object, making the array length 1.
    • .push(o2) adds the second object, making the array length 2.
    • .push(o3) adds the third object, making the array length 3.
  • After all objects are added, the final state of the array a is printed to the console, showing it contains all three objects.

 

In this example, objects are being created and their properties are set individually. Each time a property is set, its new value is output to the console. This is an alternative approach to creating objects compared to using object literals (which was seen in the previous code snippets). Here, the properties are being added to the objects one by one after the object itself is instantiated.

  • An empty array a is declared.
  • A new object o1 is created using the new Object() constructor.
  • The properties x, y, and color of the object o1 are set individually to 1.2, 3.2, and 'red', respectively.
  • Another new object o2 is created.
  • The properties x, y, and color of the object o2 are set to 2.2, 3.2, and 'blue'.
  • A third object o3 is created.
  • The properties x, y, and color of the object o3 are set to 3.2, 1.2, and 'black'.

 

This shows that an element from an array a is being accessed.

 

This example shows that individual properties of an object in an array a are being accessed.

 

This examples show that properties of the object at index 1 of the array a are accessed using bracket notation. The output for a[1]['x'] is 2.2, which is the value of the x property, and the output for a[1]['color'] is 'blue', which is the value of the color property.

 

This example demonstrates the use of the .map() method on an array a. The .map() method is used to create a new array by calling a provided function on every element in the calling array.

  • a.map(e => e.x) is called, which executes a function that takes each element e in the array a and returns its x property. The result is a new array of the x values: [1.2, 2.2, 3.2].
  • a.map(e => e.color) is called, which executes a function that takes each element e in the array a and returns its color property. The result is a new array of the color values: ['red', 'blue', 'black'].