JavaScript(JS) Arrays

ht‮w//:spt‬ww.theitroad.com

JavaScript Arrays

In JavaScript, an array is an ordered list of values that can be of any data type. Arrays are a special type of object in JavaScript, where the keys are the indices (0, 1, 2, etc.) and the values are the array elements.

Here's an example of an array in JavaScript:

let myArray = [1, 2, 3, 4, 5];

In this example, we create an array called myArray that contains the values 1, 2, 3, 4, and 5.

JavaScript arrays have several built-in methods that can be used to manipulate the elements in the array. Here are some of the most commonly used methods:

  • push: Adds one or more elements to the end of an array.
myArray.push(6, 7); // adds 6 and 7 to the end of myArray
  • pop: Removes the last element from an array and returns it.
let lastElement = myArray.pop(); // removes 7 from the end of myArray and assigns it to lastElement
  • shift: Removes the first element from an array and returns it.
let firstElement = myArray.shift(); // removes 1 from the beginning of myArray and assigns it to firstElement
  • unshift: Adds one or more elements to the beginning of an array.
myArray.unshift(0, 1); // adds 0 and 1 to the beginning of myArray
  • splice: Adds or removes elements from an array at a specified index.
myArray.splice(2, 1); // removes the element at index 2 (which is 3) from myArray
myArray.splice(2, 0, 3); // adds the value 3 back to myArray at index 2
  • slice: Returns a new array that contains a portion of the original array.
let newArray = myArray.slice(1, 3); // creates a new array that contains the values 2 and 3 from myArray

JavaScript arrays also have a length property that returns the number of elements in the array, and can be used to loop through the array using a for loop.

for (let i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

In this example, we use a for loop to iterate over each element in myArray and print it to the console.

In summary, arrays are an important data structure in JavaScript that allow you to store and manipulate ordered lists of values. They have many built-in methods for adding, removing, and manipulating elements, and can be looped over using a for loop.

Access Elements of an Array

In JavaScript, you can access individual elements of an array using their index, which starts at 0 for the first element. Here's an example:

let myArray = ["apple", "banana", "orange"];
console.log(myArray[0]); // outputs "apple"
console.log(myArray[1]); // outputs "banana"
console.log(myArray[2]); // outputs "orange"

In this example, we create an array called myArray that contains three string values. We use square brackets ([]) and the index number to access each element of the array.

You can also use variables as array indices, or perform calculations to determine the index at runtime. For example:

let myArray = ["apple", "banana", "orange"];
let index = 1;
console.log(myArray[index]); // outputs "banana"
console.log(myArray[index + 1]); // outputs "orange"

In this example, we create a variable called index that stores the value 1. We use this variable to access the second element of myArray ("banana"), and we also perform a calculation to access the third element of myArray ("orange") using index + 1.

If you try to access an index that doesn't exist in the array, you will get the value undefined. For example:

let myArray = ["apple", "banana", "orange"];
console.log(myArray[3]); // outputs undefined

In this example, we try to access the fourth element of myArray using the index 3, which doesn't exist, so we get undefined as the result.

In summary, you can access elements of an array in JavaScript using their index, which starts at 0 for the first element. You can use variables or perform calculations to determine the index at runtime, and trying to access an index that doesn't exist will return undefined.

Add an Element to an Array

To add an element to an array in JavaScript, you can use the push() method, which adds one or more elements to the end of the array. Here is an example:

let myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]

In this example, the push() method is used to add the number 4 to the end of the myArray array.

Alternatively, you can also use the splice() method to add an element at a specific index in the array. Here is an example:

let myArray = [1, 2, 3];
myArray.splice(1, 0, 4);
console.log(myArray); // Output: [1, 4, 2, 3]

In this example, the splice() method is used to add the number 4 at index 1 in the myArray array. The second argument of the splice() method specifies how many elements to remove from the array (in this case, 0), and the third argument specifies the element to add to the array.

Change the Elements of an Array

To change the elements of an array in JavaScript, you can access the array elements using their index and assign a new value to them. Here's an example:

let myArray = [1, 2, 3];
myArray[1] = 4;
console.log(myArray); // Output: [1, 4, 3]

In this example, the second element of the myArray array (which has an index of 1) is changed from the value 2 to the value 4.

You can also use methods like splice() or slice() to change array elements. Here's an example using splice():

let myArray = [1, 2, 3];
myArray.splice(1, 1, 4);
console.log(myArray); // Output: [1, 4, 3]

In this example, the splice() method is used to remove one element at index 1, and add the value 4 at the same index.

Using the slice() method, you can change elements of an array and create a new array with those changes. Here's an example:

let myArray = [1, 2, 3];
let newArray = myArray.slice();
newArray[1] = 4;
console.log(myArray); // Output: [1, 2, 3]
console.log(newArray); // Output: [1, 4, 3]

In this example, the slice() method is used to create a new array newArray that is a copy of myArray. The second element of newArray (which has an index of 1) is then changed from the value 2 to the value 4, while the original myArray remains unchanged.

Remove an Element from an Array

To remove an element from an array in JavaScript, you can use the splice() method or the filter() method.

Using splice() method:

The splice() method is used to add or remove elements from an array. To remove an element, you need to specify the index of the element to be removed and the number of elements to be removed. Here's an example:

let myArray = [1, 2, 3, 4];
myArray.splice(1, 1);
console.log(myArray); // Output: [1, 3, 4]

In this example, the splice() method is used to remove the element at index 1, which is the number 2. The second argument of the splice() method specifies the number of elements to remove, which in this case is 1.

Using filter() method:

The filter() method creates a new array with all elements that pass the test implemented by the provided function. To remove an element, you can create a new array that excludes the element to be removed. Here's an example:

let myArray = [1, 2, 3, 4];
let newArray = myArray.filter(element => element !== 2);
console.log(newArray); // Output: [1, 3, 4]

In this example, the filter() method is used to create a new array that excludes the element with the value of 2. The element parameter represents each element of the array and the callback function returns true if the element is not equal to 2.

Note that both methods modify the original array or create a new array without the removed element. If you want to remove an element and return the removed element, you can use the splice() method and access the removed element using the return value.

Array length

In JavaScript, the length property is used to get the number of elements in an array. Here's an example:

let myArray = [1, 2, 3];
console.log(myArray.length); // Output: 3

In this example, the length property is used to get the number of elements in the myArray array, which is 3.

You can also use the length property to change the length of an array. If you set the length property to a value that is less than the current length of the array, the array will be truncated and all elements with an index greater than or equal to the new length will be deleted. If you set the length property to a value that is greater than the current length of the array, the array will be extended and new elements will be added with the value of undefined. Here are some examples:

let myArray = [1, 2, 3];
myArray.length = 2;
console.log(myArray); // Output: [1, 2]

let myArray2 = [1, 2, 3];
myArray2.length = 4;
console.log(myArray2); // Output: [1, 2, 3, undefined]

In the first example, the length property of myArray is set to 2, which truncates the array and removes the element with the value of 3. In the second example, the length property of myArray2 is set to 4, which extends the array and adds a new element with the value of undefined at index 3.

Array Methods

JavaScript arrays have many built-in methods that can be used to manipulate arrays in various ways. Here are some commonly used array methods in JavaScript:

  1. push(): Adds one or more elements to the end of an array and returns the new length of the array.
let myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
  1. pop(): Removes the last element from an array and returns that element.
let myArray = [1, 2, 3];
let lastElement = myArray.pop();
console.log(lastElement); // Output: 3
console.log(myArray); // Output: [1, 2]
  1. shift(): Removes the first element from an array and returns that element.
let myArray = [1, 2, 3];
let firstElement = myArray.shift();
console.log(firstElement); // Output: 1
console.log(myArray); // Output: [2, 3]
  1. unshift(): Adds one or more elements to the beginning of an array and returns the new length of the array.
let myArray = [1, 2, 3];
myArray.unshift(0);
console.log(myArray); // Output: [0, 1, 2, 3]
  1. concat(): Joins two or more arrays and returns a new array.
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let newArray = array1.concat(array2);
console.log(newArray); // Output: [1, 2, 3, 4, 5, 6]
  1. slice(): Extracts a section of an array and returns a new array.
let myArray = [1, 2, 3, 4, 5];
let newArray = myArray.slice(1, 4);
console.log(newArray); // Output: [2, 3, 4]
  1. splice(): Adds or removes elements from an array and returns the removed elements.
let myArray = [1, 2, 3, 4, 5];
let removedElements = myArray.splice(1, 3, 6, 7, 8);
console.log(myArray); // Output: [1, 6, 7, 8, 5]
console.log(removedElements); // Output: [2, 3, 4]
  1. forEach(): Calls a function for each element in an array.
let myArray = [1, 2, 3];
myArray.forEach(function(element) {
  console.log(element);
});
// Output:
// 1
// 2
// 3

These are just a few of the many array methods available in JavaScript. You can check out the full list of array methods in the official documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Multidimensional Arrays

A multidimensional array in JavaScript is an array that contains other arrays as its elements. These arrays can be thought of as tables or matrices with rows and columns.

To create a multidimensional array, you can create an array of arrays. Here's an example of a two-dimensional array:

let myArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

In this example, myArray is a two-dimensional array with three rows and three columns. To access an element in a two-dimensional array, you need to specify both the row index and the column index. For example:

let myArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(myArray[0][0]); // Output: 1
console.log(myArray[1][2]); // Output: 6
console.log(myArray[2][1]); // Output: 8

In this example, myArray[0][0] accesses the element in the first row and first column, which has the value of 1. myArray[1][2] accesses the element in the second row and third column, which has the value of 6. And myArray[2][1] accesses the element in the third row and second column, which has the value of 8.

You can also create multidimensional arrays with more than two dimensions. For example, a three-dimensional array might represent a cube with length, width, and height. To access an element in a three-dimensional array, you would need to specify the indices for each dimension.