In this articles, we will be discussing about various methods on JavaScript arrays.
This article contains full of meaningful examples. If you are a beginner at JavaScript, I hope you'll find it very helpful.
But even as an experienced developer, this article may be useful to help you use various methods on javascript array.
Before going through arrays methods, first lets get brief about
- What is array ?
- How to create array ?
- How to Get Elements from an Array in JS ?
What is Array ?
- In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable.
- The array is a widely used data structure in JavaScript.
- In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays.
How to create array ?
let names = ['Aniket', 'Dhiraj',’Paresh’] // This will create an array of names.
let mixarray=[1,’Aniket’,12.5]
You can also use the Array constructor to create an array
const names=new Array(‘Aniket’,’Dhiraj’,’Paresh’)
How to Get Elements from an Array in JS
You can access and retrieve elements from an array using its index.
let names = ['Aniket', 'Dhiraj',’Paresh’]
let firstname = names[0] - returns Aniket
let lastname = names[names.length - 1] - returns Paresh
Now Let's discuss the various array method which is useful for developers. In this article, we will be discussing below methods
1. push ()
2. pop ()
3. sort( )
4. forEach( )
5. concat( )
6. map( )
7. filter( )
8. every( )
9. includes( )
10. slice( )
Lets discuss each method one by one and see it with examples , so that it will be helpful for you to understand its working behavior.
1. push ()
The push() method adds one or more elements to the end of an array and returns the new length of the array
Example
let names = ['Aniket', 'Dhiraj',’Paresh’];
names.push(‘Apurwa’);
Console.log(names);
//output Array ['Aniket', 'Dhiraj',’Paresh’,’Apurwa’]
names.push(‘Jivan’,’Sandeep’);
Console.log(names) ;
// output Array ['Aniket', 'Dhiraj',’Paresh’,’Apurwa’, ‘Jivan’,’Sandeep’]
Note :- push()
method adds an element to the end of the array.
If you want to add an element to the beginning of the array, you'll need to use the unshift()
method
2. pop()
The pop() method removes the last element from an array and returns that element. Every time you call the pop() method, it removes an element from the end of the array. Then it returns the removed element and changes the original array.
Example
let names = ['Aniket', 'Dhiraj',’Paresh’]
console.log(names.pop()) – output – ‘Paresh’
console.log(names) – output - Array ['Aniket', 'Dhiraj']
Note - Use the shift()
method to remove an element from the beginning of an array. Like the pop()
method, shift()
returns the removed element and changes the original array.
3. sort( )
The sort() method sorts the elements of an array in place and returns the sorted array.
The default sort order is ascending.
The default sort() method converts the element types into strings and then sorts them.
The sort() method changes the original array.
Example 1
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
Example 2
const numbers = [23, 5, 100, 56, 9, 13, 37, 10, 1]
numbers.sort();
console.log(array1);
// expected output: Array [1, 10, 100, 13, 23, 37, 5, 56, 9] .
Note - That is not the output we expect. But it happens because the default sort() method converts the elements to a string and then compares them based on the UTF-16 code unit values.
4. forEach()
The forEach() method executes a provided function once for each array element.
This method helps to loop over array by executing a provided callback function for each element in an array. Example 1 - Iterate over the elements in array
const numbers = ['a', 'b', 'c'];
numbers.forEach(x => console.log(x));
// expected output: "a"
// expected output: "b"
// expected output: "c"
Example 2 - Compute the sum of all values in an array:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Output - 125
5. concat( )
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
Example 1 - Concatenate two array
const first = [1, 2, 3];
const second = [4, 5, 6];
const merged = first.concat(second);
console.log(merged); // [1, 2, 3, 4, 5, 6]
console.log(first); // [1, 2, 3]
console.log(second); // [4, 5, 6]
Example 2
const first = [1, 2, 3];
const second = [4, 5, 6];
const third = [7, 8, 9];
const merged = first.concat(second, third);
console.log(merged); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
6. map( )
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
The map() method creates a new array by iterating through the elements and applying logic we provided in the function as an argument. Example
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
7. filter( )
The filter() method creates a new array with all elements that pass the test implemented by the provided function. The filter() method creates a new array with all the elements that satisfies the condition mentioned in the function. Example
const number=[1,2,3,4,5,6]
const filtered=number.filter(x=>x===2 || x===6)
console.log(filtered) - output [2,6]
8. every( )
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. Example
let number=[1,2,3,4,5,6,7,8,9];
// all elements greater than 3 and less than 10
let greaterThree=number.every(x=>x>3);
console.log(greaterThree) – false
let lessTen=number.every(x=>x<10)
console.log(lessTen) – return True
9. includes( )
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
10. slice( )
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
That's all for this Blog developers and with that, it's a wrap! I hope you found the article useful.
I create content about Programming, mentoring and Productivity, If this is something that interests you, please share the article with your friends and connections.
Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!
I would strongly recommend you to Check out my YouTube Channel youtube.com/c/codeasitis where i post programming video and don't forget to subscribe to my Channel. I would love to connect with you at Twitter ( twitter.com/codeasitis1 ) | Instagram ( instagram.com/codeasitis )
See you in my next Blog article, Take care!!