What are the different operations can be performed with a JavaScript Array?
Last Updated :
22 Nov, 2023
In this article, we are going to learn different operations that can be performed with an Array by using JavaScript, An array in JavaScript is a data structure that holds an ordered collection of values, which can be of any data type, using zero-based indexing for access and manipulation, including adding, removing, updating elements, sorting, filtering, mapping, reducing, and iterating through array elements for various data manipulation tasks.
Creating Array in javascript by using different operations:
Creating an array in JavaScript involves defining an ordered collection of values, accessed via zero-based indices, encapsulated within square brackets, allowing dynamic storage and manipulation of data elements.
|
let arr1 = [value1, value2, ...];
| Create arrays using square brackets and initial elements.
|
new Array(Value1, Value2, ...); or Array(Value1, Value2, ...);
| Creates arrays using the new Array() instantiation approach.
|
Array.from(object, mapFunction, thisValue)
| used to create a new array instance from a given array.
|
Array.of(element0, element1, ....)
| creates a new array with the given arguments as its elements.
|
arr.fill(value, start, end)
| used to fill the array with a given static value.
|
Example: Here is the example of above-listed methods.
JavaScript
// Using Array Literal
const languages = ['HTML', 'CSS', 'JavaScript'];
console.log("Languages are :", languages);
// Using Array Constructor
const numbers = new Array(1, 2, 3, 4, 5);
console.log("numbers:", numbers);
// Using Array.from()
const str1 = 'Geeks';
const result = Array.from(str1);
console.log(result);
// Using Array.of()
const anotherArray = Array.of(6, 7, 8);
console.log("anotherArray:", anotherArray);
// Using Array.fill()
const filledArray = new Array(5).fill(0);
console.log("filledArray:", filledArray);
OutputLanguages are : [ 'HTML', 'CSS', 'JavaScript' ]
numbers: [ 1, 2, 3, 4, 5 ]
[ 'G', 'e', 'e', 'k', 's' ]
anotherArray: [ 6, 7, 8 ]
filledArray: [ 0, 0, 0, 0, 0 ]
Here some common operations to read or access the array values in javascript:
Reading or accessing array values in JavaScript involves using indices to retrieve specific elements from the array, enabling retrieval, manipulation, and utilization of stored data elements.
|
const num1 = numbers[0];
| access individual array elements using their index.
|
const [a, b, ...restNumbers] = numbers;
| Extract array elements into separate variables succinctly.
|
array.filter(callback(element, index, arr), thisValue)
| returns the first element that satisfies a provided condition.
|
array.includes(searchElement, start)
| checks if an array includes a certain value.
|
array.indexOf(element, start)
| returns the index of the first occurrence of a value.
|
Example: In this example we are using above-mentioned method one by one.
JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Accessing by Index
const num1 = numbers[0];
const num2 = numbers[2];
console.log(num1);
console.log(num2);
// Array Destructuring
const [a, b, ...restNumbers] = numbers;
console.log(a);
console.log(b);
console.log(restNumbers);
// Array.filter()
const evenNumbers =
numbers.filter(number => number % 2 === 0);
console.log(evenNumbers);
// Array.find()
const firstEvenNumber =
numbers.find(number => number % 2 === 0);
console.log(firstEvenNumber);
// Array.includes()
const hasSeven = numbers.includes(7);
console.log(hasSeven)
// Array.indexOf()
const indexOfFive = numbers.indexOf(5);
console.log(indexOfFive)
Output1
3
1
2
[
3, 4, 5, 6,
7, 8, 9, 10
]
[ 2, 4, 6, 8, 10 ]
2
true
4
Here are some common method used to update or modification our array items in javascript:
Updating array items in JavaScript refers to changing the content of elements within an array using various methods.
|
arr1[1] = value;
| Update items by assigning new values to specific index.
|
arr.push(element0, element1, … , elementN) and arr.pop()
| Add elements to the end (push) or remove the last element (pop).
|
array.unshift(element1, element2, ..., elementX) and arr.shift()
| Add elements to the beginning (unshift) or remove the first element (shift).
|
Array.splice( index, remove_count, item_list )
| used to add or remove elements at any position.
|
arr.fill(value, start, end)
| Replace array elements with a specified value efficiently.
|
arr.reverse()
| Reverse the order of elements in the array.
|
copyWithin(target, start, end)
| Copy a portion of the array and paste it at a specified index.
|
Example: In this example we are using the above mentioned method with there basic example one by one.
JavaScript
// Original array
const arr1 = [1, 2, 3, 4, 5];
// Direct Assigarr1[1] = 6;
arr1[1] = 6;
console.log("After Direct Assignment:", arr1);
// Array.push() and Array.pop()
arr1.push(6);
console.log("After push(6):", arr1);
const poppedItem = arr1.pop();
console.log("After pop():", arr1);
console.log("Popped Item:", poppedItem);
// Array.unshift() and Array.shift()
arr1.unshift(0);
console.log("After unshift(0):", arr1);
const shiftedItem = arr1.shift();
console.log("After shift():", arr1);
console.log("Shifted Item:", shiftedItem);
// Array.splice()
arr1.splice(2, 1, 8);
console.log("After splice(2, 1, 8):", arr1);
// Array.fill()
arr1.fill(0, 1, 4);
console.log("After fill(0, 1, 4):", arr1);
// Array.reverse()
arr1.reverse();
console.log("After reverse():", arr1);
// Array.copyWithin()
arr1.copyWithin(2, 0, 2);
console.log("After copyWithin(2, 0, 2):", arr1);
Output:
After Direct Assignment: [ 1, 6, 3, 4, 5 ]
After push(6): [ 1, 6, 3, 4, 5, 6 ]
After pop(): [ 1, 6, 3, 4, 5 ]
Popped Item: 6
After unshift(0): [ 0, 1, 6, 3, 4, 5 ]
After shift(): [ 1, 6, 3, 4, 5 ]
Shifted Item: 0
After splice(2, 1, 8): [ 1, 6, 8, 4, 5 ]
After fill(0, 1, 4): [ 1, 0, 0, 0, 5 ]
After reverse(): [ 5, 0, 0, 0, 1 ]
After copyWithin(2, 0, 2): [ 5, 0, 5, 0, 1 ]
Similar Reads
Different Ways to Crate an Array of Objects in JavaScript ?
Objects in JavaScript are key-value pairs, making them suitable for representing structured data. Also, an array in JavaScript is a versatile data structure that can hold a collection of values. When dealing with objects, an array can be used to store multiple objects. An array of objects allows you
3 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive dat
3 min read
What is the Difference Between Arguments object and Rest parameters in JavaScript?
The arguments and Rest Parameters is crucial for the writing efficient and modern JavaScript code. The arguments object has been traditionally used in functions to the access the parameters passed to them. However, with the introduction of the ES6 Rest Parameters provide the more readable and flexib
2 min read
Difference Between Array.prototype.map() and Array.prototype.flatMap() in JavaScript
In JavaScript, Array.prototype.map() and Array.prototype.flatMap() are both the methods used to the transform elements in arrays but they differ in their behaviors regarding handling and flattening of the nested arrays.What is Array.prototype.map()?The map() method creates a new array populated with
3 min read
What are the builtin strings in JavaScript ?
A sequence of letters, special characters, numbers, etc., or a combination of all of them is known as a string. Strings are created by enclosing the string characters within a single quote (') or within double quotes ("). Syntax: var myString = 'Good Morning123!'; // Single quoted string var myStrin
3 min read
Difference Between JavaScript Arrays and Objects
Below are the main differences between a JavaScript Array and Object.FeatureJavaScript ArraysJavaScript ObjectsIndex TypeNumeric indexes (0, 1, 2, ...)Named keys (strings or symbols)OrderOrdered collectionUnordered collectionUse CaseStoring lists, sequences, ordered dataStoring data with key-value p
1 min read
How to Add the Numbers in a JavaScript Array?
Adding the numbers in a JavaScript array is a common operation, particularly in tasks involving data aggregation or mathematical calculations. This process involves iterating through the array and summing its elements. JavaScript provides multiple methods to achieve this, ranging from traditional lo
2 min read
What is the difference between unshift() and Push() method in JavaScript?
JavaScript Unshift() method is very much similar to the push() method but the difference is that the unshift() method adds the elements at the very beginning of the array whereas the push() method adds at the end of the array. Javascript Array unshift() method: The JavaScript Array unshift() Method
2 min read
Different Ways to Use Array Slice in JavaScript
In this article, we will see the different ways to use the Array slice method in Javascript. Using Array Slice in JavaScript refers to the technique of extracting a specified portion of an array, defined by start and end indices, to create a new array containing those selected elements. Syntaxarr.sl
4 min read
Find the OR and AND of Array elements using JavaScript
Given an array and the is task to find the OR and AND operations of the values of an Array using JavaScript. These are the following methods: Using simple for loopUsing reduce() MethodApproach 1: Using simple for loop It uses a simple method to access the array elements by an index number and use th
2 min read