JS Arrays

JS Arrays

JS Arrays

In JavaScript, an array is a collection of elements, which can be of any data type. You can use arrays to store lists of items, such as names, numbers, or objects. Here’s an example of how to create an array:

				
					let fruits = ['apple', 'banana','orange'];
				
			

In this example, we’ve created an array called fruits that contains three string elements. Here are some common operations you can perform on arrays in JavaScript:

1.Accessing elements: You can access individual elements of an array using their index (starting from 0):

				
					console.log(fruits[0]); //Output: "apple"
				
			
  1. Changing elements: You can change an element in an array by assigning a new value to its index:
				
					fruits[1] = 'kiwi';

console.log(fruits); // Output:["apple", "kiwi", "orange"]
				
			
  1. Adding elements: You can add elements to the end of an array using the push() method:
				
					fruits.push('pear');

console.log(fruits); // Output:["apple", "kiwi", "orange", "pear"]
				
			
  1. Removing elements: You can remove elements from the end of an array using the pop() method:
				
					fruits.pop();

console.log(fruits); // Output:["apple", "kiwi", "orange"]
				
			
  1. Looping through elements: You can use a for loop to iterate over the elements of an array:
				
					for (let i = 0; i <
fruits.length; i++) {

console.log(fruits[i]);

}

// Output:

// "apple"

// "kiwi"

// "orange"
				
			
  1. Array length: You can find the number of elements in an array using the length property:
				
					console.log(fruits.length); //Output: 3


				
			

These are just a few examples of what you can do with arrays in JavaScript. By using arrays, you can create more powerful and flexible applications that can handle lists of data.

JS Array Methods:

JavaScript provides a wide range of methods for manipulating arrays. Here are some of the most commonly used methods:

       1. push: adds one or more elements to the end of an array and returns the new length of the array.

				
					let arr =[1, 2, 3];

arr.push(4);
console.log(arr); // [1, 2, 3, 4]
				
			

      2. pop: removes the last element from an array and returns that element.

				
					let arr =[1, 2, 3];

let last =arr.pop();
console.log(last);// 3
console.log(arr); // [1, 2]
				
			
  1. unshift: adds one or more elements to the beginning of an array and returns the new length of the array.
				
					let arr =[1, 2, 3];

arr.unshift(0);

console.log(arr);// [0, 1, 2, 3]
				
			
  1. shift: removes the first element from an array and returns that element.
				
					let arr =[1, 2, 3];

let first =arr.shift();

console.log(first);// 1
console.log(arr); // [2, 3]
				
			

       5. slice: returns a new array with a portion of the original array, starting from the specified start index and ending at the specified end index.

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

let sliced= arr.slice(1, 4);

console.log(sliced); // [2, 3, 4]
				
			
  1. splice: changes the contents of an array by removing or replacing existing elements and/or adding new elements.
				
					let arr =[1, 2, 3, 4, 5];

arr.splice(2,2, 'a', 'b');

console.log(arr);// [1, 2, 'a', 'b', 5]
				
			
  1. concat: joins two or more arrays and returns a new array.
				
					let arr1 =[1, 2];

let arr2 =[3, 4];

let arr3 =arr1.concat(arr2);

console.log(arr3);// [1, 2, 3, 4]
				
			
  1. indexOf: returns the first index at which a given element can be found in the array, or -1 if it is not present.
				
					let arr =[1, 2, 3, 2];

let index =arr.indexOf(2);

console.log(index);// 1
				
			
  1. filter: creates a new array with all elements that pass the test implemented by the provided function.
				
					let arr =[1, 2, 3, 4, 5];

letfiltered = arr.filter(functi(element) {

  return element > 3;
});

console.log(filtered);// [4, 5]
				
			
  1. map: creates a new array with the results of calling a provided function on every element in the array.
				
					let arr =[1, 2, 3];

let mapped= arr.map(function(element) {

  return element * 2;

});

console.log(mapped);// [2, 4, 6]
				
			

Sorting Arrays:

JavaScript provides several methods for sorting arrays. Here are some commonly used methods:

sort(): sorts the elements of an array in place and returns the sorted array. By default, the elements are sorted in ascending order based on their string Unicode code points.

				
					let arr =[3, 1, 4, 2];

arr.sort();

console.log(arr); // [1, 2, 3, 4]
				
			

To sort an array in descending order, you can use the reverse() method after sorting the array in ascending order:

				
					let arr =[3, 1, 4, 2];

arr.sort();

arr.reverse();

console.log(arr);// [4, 3, 2, 1]
				
			

You can also provide a compare function to the sort() method to specify a custom sorting order. The compare function takes two arguments (a and b) and returns a negative value if a should come before b, a positive value if a should come after b, and 0 if a and b are equal. For example, to sort an array of numbers in descending order, you can write:

				
					let arr =[3, 1, 4, 2];

arr.sort(function(a,b) {

  return b - a;

});

console.log(arr);// [4, 3, 2, 1]
				
			
  1. reverse(): reverses the order of the elements in an array in place and returns the reversed array.
				
					let arr =[1, 2, 3];

arr.reverse();

console.log(arr);// [3, 2, 1]
				
			
  1. slice(): returns a new array with the elements of the original array sorted. The original array is not modified.
				
					let arr =[3, 1, 4, 2];

let sorted= arr.slice().sort();

console.log(sorted);// [1, 2, 3, 4]

console.log(arr);// [3, 1, 4, 2]
				
			

Note that slice() is used to create a shallow copy of the original array before sorting it. This is necessary because sort() modifies the original array in place.

  1. localeCompare(): compares two strings according to the current locale and returns a value indicating their relative order. This method is often used as the compare function for sorting arrays of strings in a locale-sensitive way. For example:
				
					let arr =['banana', 'apple', 'orange'];

arr.sort(function(a,b) {

  return a.localeCompare(b);

});

console.log(arr);// ['apple', 'banana', 'orange']
				
			

This sorts the array in ascending alphabetical order according to the current locale.

Array Iteration:

Array iteration refers to the process of looping over the elements of an array and performing some action on each element. JavaScript provides several ways to iterate over arrays:

  1. for loop: a traditional loop that iterates over the elements of an array using an index variable.
				
					let arr =[1, 2, 3];

for (let i= 0; i < arr.length; i++){

  console.log(arr[i]);

}
				
			
  1. forEach() method: a method that calls a function once for each element in the array.
				
					let arr =[1, 2, 3];

arr.forEach(function(element){

  console.log(element);

});
				
			

The forEach() method takes a callback function as an argument, which is called once for each element in the array. The callback function takes three arguments: the current element, the index of the current element, and the array being iterated.

  1. ..of loop: a loop that iterates over the values of an iterable object, including arrays.
				
					let arr = [1, 2, 3];

for (let element of arr) {

  console.log(element);

}
				
			

The for…of loop is simpler than the for loop because it does not require an index variable.

  1. map() method: a method that creates a new array by calling a function on each element in the original array.
				
					let arr =[1, 2, 3];

let doubled= arr.map(function(element) {

  return element * 2;

});

console.log(doubled);// [2, 4, 6]
				
			

The map() method takes a callback function as an argument, which is called once for each element in the array. The callback function should return the transformed value of the current element.

  1. filter() method: a method that creates a new array with all elements that pass a test implemented by a callback function.
				
					let arr =[1, 2, 3, 4, 5];

let even =arr.filter(function(element) {

  return element % 2 === 0;

});

console.log(even);// [2, 4]
				
			

The filter() method takes a callback function as an argument, which is called once for each element in the array. The callback function should return true for elements that should be included in the filtered array.

  1. reduce() method: a method that applies a callback function to each element of an array to reduce the array to a single value.
				
					let arr =[1, 2, 3, 4, 5];

let sum =arr.reduce(function(total, element) {

  return total + element;

}, 0);

console.log(sum);// 15
				
			

The reduce() method takes a callback function as an argument, which is called once for each element in the array. The callback function should take two arguments: the accumulated value (also known as the “reducer”) and the current element. The accumulated value is initialized to the second argument passed to the reduce() method (in this case, 0).

Each of these methods provides a different way to iterate over arrays and perform operations on their elements.

Array Const:

An array is a collection of elements of the same data type stored sequentially in memory. In JavaScript, an array can be created using square brackets [] and can hold any type of data, including other arrays.

A const declaration is used to create a variable whose value cannot be reassigned. When used with an array, const ensures that the variable reference cannot be reassigned to a new array, but the content of the array can still be modified.

For example, consider the following code:

				
					constmyArray = [1, 2, 3];

myArray[0]= 4;

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

In this example, myArray is declared as a constant array containing the elements 1, 2, and 3. Even though it is declared as a const, we can still modify its elements. We change the value of the first element to 4, and the output of the console.log() statement shows that the content of the array has been modified accordingly.

However, if we try to assign a new value to myArray, we will get an error:

				
					constmyArray = [1, 2, 3];

myArray =[4, 5, 6]; // Error: Assignment to constant variable. 
				
			

This error occurs because const prevents the variable reference from being reassigned to a new array

Join To Get Our Newsletter
Spread the love