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"
fruits[1] = 'kiwi';
console.log(fruits); // Output:["apple", "kiwi", "orange"]
fruits.push('pear');
console.log(fruits); // Output:["apple", "kiwi", "orange", "pear"]
fruits.pop();
console.log(fruits); // Output:["apple", "kiwi", "orange"]
for (let i = 0; i <
fruits.length; i++) {
console.log(fruits[i]);
}
// Output:
// "apple"
// "kiwi"
// "orange"
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]
let arr =[1, 2, 3];
arr.unshift(0);
console.log(arr);// [0, 1, 2, 3]
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]
let arr =[1, 2, 3, 4, 5];
arr.splice(2,2, 'a', 'b');
console.log(arr);// [1, 2, 'a', 'b', 5]
let arr1 =[1, 2];
let arr2 =[3, 4];
let arr3 =arr1.concat(arr2);
console.log(arr3);// [1, 2, 3, 4]
let arr =[1, 2, 3, 2];
let index =arr.indexOf(2);
console.log(index);// 1
let arr =[1, 2, 3, 4, 5];
letfiltered = arr.filter(functi(element) {
return element > 3;
});
console.log(filtered);// [4, 5]
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]
let arr =[1, 2, 3];
arr.reverse();
console.log(arr);// [3, 2, 1]
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.
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:
let arr =[1, 2, 3];
for (let i= 0; i < arr.length; i++){
console.log(arr[i]);
}
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.
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.
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.
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.
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
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.