Greetings readers, "Are you tired of juggling multiple variables to manage your data? Say goodbye to the hassle and hello to arrays! As a web developer, I can attest to the power and convenience of arrays in JavaScript. These little wonders allow you to store and manipulate collections of data in a single variable, streamlining your code and making your life easier. In this comprehensive guide, I'll show you how to master arrays in JavaScript, whether you're a newbie or a seasoned pro. From basic concepts to advanced techniques, this guide has everything you need to become an array ninja. So, grab your coffee & let's dive into the exciting world of arrays in JavaScript!"
What is an Array???
An array is a data structure that stores a collection of elements, which can be of any data type including numbers, objects, strings, and other arrays as well. One of the Characteristics of an Array is, it is mutable, which means that you can modify the elements of an array. You can add, remove, or change the elements of an array after it has been created. In JavaScript, arrays are created using square brackets []. The elements of an array are uniquely indexed, starting from 0. This means that the first element of an array has an index of 0, the second element has an index of 1, and so on. You can access the elements of an array using their index, like this:
let myArray = [1, "Hello", [1,2,3]];
console.log(myArray[0]); // Output: 1
console.log(myArray[1]); // Output: Hello
console.log(myArray[2]); // Output: [1,2,3]
How to create an array in javascript ??
JavaScript provides various methods to create arrays. Let's explore them one by one:
Array Literal: The easiest way to create an array in JavaScript is to use an array literal. An array literal is a comma-separated list of values enclosed in square brackets [].
let myArray = [2,3,4,"Ram",{name: "Rohan", age:32}];
you can also modify any value of the array if you want to after its creation,
myArray[0]=6; // now if you try to print value of myArray at index 0 it will print 6.
you can create an empty as well, just write the name and assign it empty square brackets :
let myArray = [];
Array Constructor: You can also create an array using the Array constructor. The Array constructor takes one or more arguments and returns a new array containing those arguments.
Note that - if you pass a single argument to the Array constructor, it creates an array with a length equal to that argument.
let newArray = new Array(1, 2, 3); //console.log(newArray) -> Output: [1,2,3]
Array.of() Method: The Array.of() method creates a new array with a variable number of arguments.
let programmingLanguage = Array.of("Cpp","Java","Javascript","Go lang"); //console.log(programmingLanguage) //Output: ["Cpp","Java","Javascript","Go lang"]
Note - It is mostly similar to the constructor method but there is one difference like if we pass only one value in Array.of() then it will create an array consisting of that single value but as mentioned above in case of the constructor, it will create an array with a length equal to that passed value
let newArray = new Array(2); console.log(newArray) //Output: [,] > emptyx2 let arr = Array.of(2); console.log(arr); // Output: [2]
Array.from() Method: The Array.from() method creates a new array from an array-like or iterable object.
let myArray = Array.from('hello'); console.log(myArray); // Output: ['h', 'e', 'l', 'l', 'o']
Spread Operator: The spread operator can be used to create a new array by expanding the elements of an existing array.
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let combinedArray = [...arr1, ...arr2]; console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
split method: This split() method is used to split a string into an array of substrings based on a specified separator.
Syntax: str.split(separator, limit) where separator & limit are optional.
split() method does not change the original string. Instead, it returns a new array of substrings. If the separator is not found in the string, the split method will return an array containing the original string as the only element.
let myString = "apple,banana,orange"; let myArray = myString.split(","); //separator is comma(,) , so whenever it see comma it will split that string according to that. console.log(myArray); // Output: ["apple","banana","mango"]
Javascript methods:
JavaScript provides a variety of methods related to arrays.
push() method:
This method adds one or more elements to the end of an array & returns the modified length of the array after pushing new elements.
let multipleOfFive = [5,10,15]; //Push one element multipleOfFive.push(20); // return -> 4 console.log(multipleOfFive); // Output: [5,10,15,20] //Pushing multiple element multipleOfFive.push(25,30,35); // return -> 7 console.log(multipleOfFive); // Output: [5,10,15,20,25,30,35]
pop() method:
This method removes the last element from an array & returns that removed element.
let multipleOfFive = [5,10,15]; console.log(multipleOfFive.pop()); // Output: 15 console.log(multipleOfFive); // Output: [5,10]
shift() method:
This method removes the first element from an array & returns that removed element.
let multipleOfFive = [5,10,15]; console.log(multipleOfFive.shift()); // Output: 5 console.log(multipleOfFive); // Output: [10,15]
unshift() method:
This method adds one or more elements to the beginning of an array & returns the modified length of the array after pushing new elements.
let multipleOfFive = [5,10,15]; //unshift one element multipleOfFive.unshift(20); // return -> 4 console.log(multipleOfFive); // Output: [20,5,10,15] //unshift multiple element multipleOfFive.unshift(25,30,35); // return -> 7 console.log(multipleOfFive); // Output: [25,30,35,20,5,10,15]
splice() method:
The splice() method can be used to add or remove elements from an array at a specified index. It takes three arguments:
the index at which to start changing the array
the number of elements to remove (optional)
the elements to add (optional)
The method returns an array containing the removed elements (if any). The original array is modified in place.
let multipleOfFive = [5,10,15];
console.log(multipleOfFive.splice(1,1,20)); // Output: 10
console.log(multipleOfFive); // Output: [5,20,15]
// Above code means that we are starting from index 1 and moving till the next 1 element and we will remove that and add 20 at that removed element place
slice() method:
The slice() method returns a new array that contains a portion of the original array, specified by start and end indices. The original array is not modified.
let multipleOfFive = [5,10,15,20,25,30]; let newArray = multipleOfFive.splice(1,3); console.log(multipleOfFive); // Output: [5,10,15,20,25,30] console.log(newArray); // Output: [10,15]
includes() method:
The includes() method determines whether an array contains a certain value among its entries or not. It returns true if the array contains the value, and false otherwise.
let multipleOfFive = [5,10,15,20,25,30]; console.log(multipleOfFive.includes(15)); //Output: true console.log(multipleOfFive.includes(55)); //Output: false
indexOf() method:
The indexOf() method returns the first index at which a given element that is passed in the argument is found in an array, or -1 if it is not present in that array.
let multipleOfFive = [5,10,15,20,15,30]; console.log(multipleOfFive.indexOf(15)); //Output: 2 console.log(multipleOfFive.indexOf(55)); //Output: -1
lastIndexOf() method:
The lastIndexOf() method returns the index of the last occurrence of a specified value in an array. It searches the array backward, starting at the specified index.
let multipleOfFive = [5,10,15,20,15,30]; console.log(multipleOfFive.lastIndexOf(15)); //Output: 4
concat() method:
This method is used to merge two or more arrays without modifying the existing array. It returns a new array containing all elements from the original arrays.
let multipleOfFive = [5,15,25]; let multipleOfTen = [10,20,30]; let concatedArray = multipleOfFive.concat(multipleOfTen); console.log(concatedArray); //Output: [5,10,15,20,25,30]
reverse() method:
The reverse() method is used to reverse the order of elements in an array.
let multipleOfFive = [5,10,15,20,15,30]; multipleOfFive.reverse(); console.log(multipleOfFive); //Output: [30,25,20,15,10,5]
toString() method:
This method returns a string representing the specified array and its elements.
let multipleOfFive = [5,10,15,20,15,30]; let str = multipleOfFive.toString(); console.log(str); //Output: "5,10,15,20,15,30"
join() method:
This method returns a string with all array elements concatenated into it with a specified separator.
let multipleOfFive = [5,10,15,20,15,30]; let str = multipleOfFive.join("-"); console.log(str); //Output: "5-10-15-20-15-30"
some() method:
This method tests whether at least one element in the array passes the provided callback function. It returns a Boolean value.
let multipleOfFive = [5,10,15,20,15,30]; let hasSomeElement = multipleOfFive.some(function(ele) { return ele > 20; }); console.log(hasSomeElement); //Output: true
every() method:
This method tests whether all elements in the array pass the provided function. It returns a Boolean value.
let multipleOfFive = [5,10,15,20,15,30]; let hasEveryElement = mmultipleOfFive.every(function(ele) { return ele > 20; }); console.log(hasEveryElement); //Output: false
flat() method:
This method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth and that depth should be passed in the argument else it will take default which is 1 level.
let multipleOfFive = [5,[10,15,[20,15,[30]]]]; let flatedArray = multipleOfFive.flat(3); console.log(flatedArray); //Output: [5,10,15,20,15,30]
find() method:
This method returns the value of the first element in an array that satisfies the provided testing function. The provided function is called with three arguments:
the current element being processed
the index of the current element being processed
the array on which find() was called
let multipleOfFive = [5,10,15,20,15,30];
let foundElement = multipleOfFive.find(function(ele, index, arr) {
return ele > 10;
});
console.log(foundElement); //Output: 15
forEach() method:
The forEach() method executes a provided function once for each element in an array, in order. The provided function is called with three arguments:
the current element being processed
the index of the current element being processed
the array on which forEach() was called
let multipleOfFive = [5,10,15,20,25,30];
multipleOfFive.forEach((num,index,arr) => console.log(num));
// it will console.log each element
map() method:
The map() method creates a new array with the results of calling a provided function on every element in the calling array. The provided function is called with three arguments:
the current element being processed
the index of the current element being processed
the array on which map() was called
let multipleOfFive = [5,10,15,20,25,30];
let multipleOfTen = multipleOfFive.map((ele,index,arr) => {
return ele*2;
})
console.log(multipleOfFive); //output: [5,10,15,20,25,30]
console.log(multipleOfTen); //output: [10,20,30,40,50,60]
filter() method:
This method creates a new array with all elements that pass the test implemented by the provided function. The provided function is called with three arguments:
the current element being processed
the index of the current element being processed
the array on which filter() was called
let multipleOfFive = [5,10,15,20,25,30];
let filteredArray = multipleOfFive.filter((ele,index,arr) => {
return ele%2 === 0 ;
})
console.log(filteredArray) //Output: [10,20,30]
reduce() method:
This method executes a provided function on each element of an array, resulting in a single output value. The provided function is called with four arguments:
the accumulator (the value returned from the previous call to the function)
the current element being processed
the index of the current element being processed
the array on which reduce() was called
let multipleOfFive = [5,10,15,20,25,30];
let sum = multipleOfFive.reduce(function(acc, curr, index, arr) {
return acc + curr;
});
console.log(sum); // Output: 95
Conclusion:
Arrays are a fundamental data structure in JavaScript that allows you to store and manipulate collections of data. JavaScript provides a variety of built-in methods that make it easy to work with arrays, from adding and removing elements to transforming and iterating over their contents. By understanding these methods and how to use them effectively, you can greatly enhance your ability to write concise and efficient code.
Whether you're building a small web application or a large-scale enterprise system, arrays are an essential tool that you'll use time and time again. By mastering their methods, you'll be able to write more powerful and expressive code that can handle complex data structures with ease.