The JavaScript Array class is a global object that is used in the construction of arrays. In Javascript, Arrays are listed like objects, and are remarkable flexibility. We can easily, sort, add, and remove items according to their position.
Javascript Array object
In Javascript array is a type of object that is used to store multiple values in a single variable. Each value has a numeric index that may contain data of any data type Booleans, numbers, strings, functions, objects, and even another array.
Syntax of Javascript Array object
const framworks = ['Angular', 'React', 'Vue']
How to create Javascript array object
In Javascript, we can easily create an array object, two of the most common ways to create an array.
- Using new keyword.
- Using square braces [] array literal
const myArray = new Array(); // Empty object
const myArray = [];
Initializing an Array
In the previous example code for creating an array, we have an empty array. We can assign data to an array object while creating it.
const pLanguages = ['C', 'Javascript', 'Java'];
const pLanguages = new Array("C", "Javascript", "Java", "C++");
We can add array data after an array object is created.
const pLanguages = [];
pLanguages[0] = 'C';
pLanguages[1] = 'Javascript';
pLanguages[2] = 'Java';
pLanguages[3] = 'C++';
Javascript Array object properties
As an array is like an object-like list, it has the following properties.
- length: We can length property on arrayObject name to get a length of an array. As for our example, pLanguages.length will return integer 4.
- index: As in another programming, the array index starts at zero to get the individual item in the array we can use an index as follow. pLanguages[1] and 1 is the index.
- constructor: Is the reference to array function which used to create array object.
- prototype: We can see in the previous image a prototype of the array object, and it has a list of objects and properties.
Javascript array object looping its items
We can loop javascript array objects using for loop and forEach loop. In this example, we are using forEach on the array object.
const pLanguages = ['C', 'Javascript', 'Java'];
pLanguages.forEach((item, index) => {
console.log('Index :' +index + ' ' + item);
});
Output:
Index 0 : C
Index 1 : Javascript
Index 2 : Java
In the forEach loop, we pass each item with an index in function to print its value. Where item represents an element of an array at a particular moment and index is the index value of an element.
Javascript object methods
Javascript array has lots of pre-made methods which are ready to use, we can use this method to perform a variety of activities like sorting, adding items, removing items, and more. Here we had listed some of the most common methods used on Javascript array objects.
Method | Description |
concat | Joins multiple arrays and returns a new array of combined values. |
forEach | We had just used the above, iterate, and call a function on each array element. |
join | Joins all the array elements together into a string |
indexOf | Return index of array element if it is present otherwise return -1. |
splice | Adds or deletes the specified index(es) to or from the array. |
sort | Sort array element based on function definition is specified or sorted by alphabetical based. |
slice | Extracts a section of an array and returns a new array. |
lastIndexOf | Return the last element of the array. |
filter | Creates a new array with all elements that pass the test implemented by the provided function. |
map | Creates a new array with the results of calling a provided function on every element in the calling or existing array. |
pop | Remove the last element from an array and return the removed element. |
shift | Remove the first element from an array and return the removed element. |
push | Add a new element at the last of an array and return the array length. |
unshift | Add a new element at the first of an array and return the array length. |
reverse | Reverse array in decreasing order. |
find | To find an element in an array using its properties and return element if found and return undefined if not found matching element in an array object. |
reduce | Apply a function simultaneously against two values of the array (from left-to-right) to reduce it to a single value. |
some | Check if an element exists in an Array object if it exists return true and false on no match found. |
Create an array object
const books = ['C', 'Javascript', 'Java'];
We can easily get number of element in an array object:
console.log(books.length); // 3
const newLength = books.push('C++'); // O/P 4 new array length
books.reverse(); OP C++, Java, Javascript, C
Javascript object method splice() example
The splice() method adds/removes items to/from an array, returns the removed item(s), and changes the content of an array, adding new elements while removing old elements. The splice method adds a new element to the existing array and removes an element from to existing array and then adds the removed element to the new array. Syntax of slice method
array.splice(index, howMany, [item1][, …, itemN]);
Where index − Index at which to start changing the array. howMany − total number of old array elements to remove. If howMany is 0, no elements are removed. item1, …, itemN – Optional, and the elements to be added to the array. If you don’t specify any elements, the splice simply removes the elements from the array.
<body>
<p>Click the button to add and remove elements.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const companies = ["Apple", "Google", "Facebook", "IBM"];
document.getElementById("demo").innerHTML = companies;
function myFunction() {
companies.splice(2, 1, "Infosys", "TCL");
document.getElementById("demo").innerHTML = companies;
}
</script>
</body>
In this example, we are removing one element at the second index and adding two new an element at companies array index 2. The resulting array element of companies is Apple, Google, Infosys, TCL, and IBM, and where second element Facebook is removed from an array list.
Example 2: Here we are removing the element from the existing array and adding the removed element to a new array called sliced.
<body>
<p>Click the button to add and remove elements.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
New sliced array
<p id="sliced"></p>
<script>
function myFunction() {
const oldArray = ['zero', 'one', 'two', 'three'];
const sliced = oldArray.splice(2, 3);
document.getElementById("demo").innerHTML = oldArray;
document.getElementById("sliced").innerHTML = sliced;
}
</script>
</body>
The output of the above code, oldArray :[ “zero”, ”one”] and new sliced: “[two”, ”three”].
Javascript object methods find() example
Javascript array object to find an element using its element property. In our next example, we have an array object containing a list array object in it. Here is an array of array object countries, each element in the countries contains an array object.
const countries = [
{
name: "France",
area: 640679,
population: 64979548,
},
{
name: "India",
area: 3287263,
"population": 1324171354,
},
{
name: "Germany",
area: 357114,
population: 82114224,
},
{
name: 'Canada',
area: 9976140,
population: 36624199
},
{
name: 'United States',
area: 9629091,
population: 324459463
}
];
Let’s used the find method to find detailed information about the country India using its name.
let country = countries.find(item => item.name === "India");
let temp = `Name : ${ country.name } <br> Area : ${ country.area } <br> Population : ${ country.population }`;
document.getElementById("demo").innerHTML = temp;
Javascript object methods map() example
The map method creates a new array with the results of calling a provided function on every element in the calling or existing array. We have to supply an array, run that through a function (which can be used to perform certain operations on the supplied array – such as, for example, converting each array item value to upper case), and subsequently returns a new array once completed.
var numbers = [1, 4, 6, 10];
var doubles = numbers.map(function(x) {
return x * 2;
});
// doubles is now [2, 8, 12, 20]
// numbers is still [1, 4, 6, 10]
//ES6 example
const numbers = [2, 14, 18, 22];
const halves = numbers.map(x => x / 2);
// halves is now [1, 7, 9, 11]
// numbers is still [2, 14, 18, 22]
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
Javascript object methods filter() example
Javascript filter method to retrieve specific values from an array object if the condition is met.
const newArr = [
{ id: 1, country: "England" },
{ id: 2, country: "Scotland" },
{ id: 3, country: "Wales" },
{ id: 4, country: "Northern Ireland" },
{ id: 5, country: "Republic of Ireland" },
{ id: 6, country: "France" },
{ id: 7, country: "Germany" },
{ id: 8, country: "Italy" },
{ id: 9, country: "Spain" },
{ id: 10, country: "Belgium" },
{ id: 11, country: "Holland" },
{ id: 12, country: "Czech Republic" }
];
const countries = newArr.filter((x) => {
if(x.id % 4 === 0) {
return x;
}
});
console.dir(countries);
// Outputs following to web console
[{id: 4, country: “Northern Ireland”},
{id: 8, country: “Italy”},
{id: 12, country: “Czech Republic”}]
Related posts
- Javascript Map and Join function
- JavaScript String – replace() Method
- Functional Programming in JavaScript
- The JavaScript an Array function