Your cart
  • IMG
    {{cart_item.name}}
    {{cart_item.variation_attribute_name}}: {{cart_item.variation_attribute_label}}
    {{cart_item.item_unit}}: {{ setCurrency(cart_item.price)}}
    {{ setCurrency(cart_item.price*cart_item.quantity)}}
    Invalid quantity more than stock
Total :
{{setCurrency(cart.sub_total)}}

There is no item in the cart. If you want to buy, Please click here.

JavaScript Array : How to Create and Access an array, array as objects in details.

Created by :
Array, Programming
article
Programming, Software and application
968
2020-10-14 16:14:13

For any programming language, array is a very important topic. If someone want to be expert in a specific programing language, he/she must expert in array. In JavaScript, array is more important because everything in JavaScript treat as Array. So without clear know on Array, you can not sound in JavaScript. What is array and how can define and create array in JavaScript, What are the JavaScript array methods and properties, I will try to discuss in this articles.


What is Array?

-The Array object is used to store multiple values in a single variable.

- An array can hold many values under a single name, and you can access the values by referring to an index number.


Example of Array:

var colors = ["Red", "Green", "Blue"]; 
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];


Why Array?

Objects allow you to store keyed collections of values. That’s fine. But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.


It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.


There exists a special data structure named Array, to store ordered collections.

 

Create an Array

An array can be created in three ways. The following code creates an Array object called LanguageName:

 

1. Regular:

 var LanguageName =new Array();
 LanguageName [0]="Bangla";     
 LanguageName [1]="English";
 LanguageName [2]="Spanish";

Here 0,1,2 are index of array and this index is unique for an array.

 

2. Condensed:

 var LanguageName =new Array("Bangla"," English"," Spanish");

here automatically generate 0 based index.

 

3. Literal:

 var LanguageName ("Bangla"," English"," Spanish"];

here automatically generate 0 based index.

 

Access an array

1. We can normally access array with array index such as array is

var LanguageName = ["Bangla"," English"," Spanish"];

  we can access second element which is English by:

var myLanguage =  LanguageName[1];

This statement modifies the 3rd  element in LanguageName:

LanguageName[2] = "Japanese";

Accessing First element: 

fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];

Accessing Last element: 

fruits = ["Banana", "Orange", "Apple", "Mango"];
var last = fruits[fruits.length - 1];


2. Iterate over elements, a loop over all indices is usually used.

The following example demonstrates iterating with for loop.


var LanguageName =["Bangla"," English"," Spanish"];
for(var i=0; i< LanguageName.length; i++) {
    alert(LanguageName[i])
}

 

You can also use the Array.forEach() function:

var  fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.forEach(element => {
 console.log(element);
});


Using callback function 

fruits.forEach(myFunction);
function myFunction(value) {
  console.log(value); 
}


Using For..In

for...in is used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable.

 Don’t forget, arrays are objects too — which means we can also use the for...in loop on Arrays.  

var  fruits = ["Banana", "Orange", "Apple", "Mango"];
for (let i in fruits) {  
 console.log(fruits[i])
} 


And since each character in a string has an index, we can even use for...in on strings. Check this out:

const string = 'hello';
for (let character in string) {  
  console.log(string[character])
}


Multi dimensional Array

JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops

The following code example illustrates the array-of-arrays technique. First, this code creates an array f. Then, in the outer for loop, each element of f is itself initialized as new Array(); thus f becomes an array of arrays. In the inner for loop, all elements f[i][j] in each newly created "inner" array are set to zero.

var iMax = 20;
var jMax = 10;
var f = new Array();
 
for (i=0;i
 f[i]=new Array();
 
 for (j=0;j
  f[i][j]=0;
 
 }
 
}

 

Arrays as Objects

In JavaScript, objects and arrays are handled almost identically, because arrays are merely a special kind of object.

 

All JavaScript variables are objects. Array elements are objects. Functions are objects.

 

Both objects and arrays can have properties and methods.

 

Arrays have a length property but objects do not. When you assign a value to an element of an array whose index is greater than its length (for example, myArray[100] = "hello"), the length property is automatically increased to the new length. Similarly, if you make the length property smaller, any element whose index is outside the length of the array is deleted.

 

// An array with three elements
var myArray = new Array(3);
 
// Add some data
myArray[0] = "Hello";
myArray[1] = 42;
myArray[2] = new Date(2000, 1, 1);

document.write("original length is : " + myArray.length); 
document.write(" ");

// Add some expando properties
myArray.expando = "JavaScript!";
myArray["another Expando"] = "Windows";
 
// This will still display 3, since the two expando properties
// don't affect the length.
document.write("new length is : " + myArray.length);

  

// Output:

// original length is: 3

// new length is : 3

 

Array Methods and Properties

The Array object has predefined properties and methods:

 var x= LanguageName.length             // the number of elements in myCars

 var y= LanguageName.indexOf("Volvo")   // the index position of "Volvo"

 All Array Methods and Properties


Very Common JavaScript Array Methods

  • concat(): Merge two or more arrays, and returns a new array.
  • copyWithin(): Copies part of an array to another location in the same array and returns it.
  • entries(): Returns a key/value pair Array Iteration Object.
  • every(): Checks if every element in an array pass a test in a testing function.
  • fill(): Fill the elements in an array with a static value.
  • filter(): Creates a new array with all elements that pass the test in a testing function.
  • find(): Returns the value of the first element in an array that pass the test in a testing function.
  • findIndex(): Returns the index of the first element in an array that pass the test in a testing function.
  • forEach(): Calls a function once for each array element.
  • from(): Creates an array from an object.
  • includes(): Determines whether an array includes a certain element.
  • indexOf(): Search the array for an element and returns its first index.
  • isArray(): Determines whether the passed value is an array.
  • join(): Joins all elements of an array into a string.
  • keys(): Returns a Array Iteration Object, containing the keys of the original array.
  • lastIndexOf(): Search the array for an element, starting at the end, and returns its last index.
  • map(): Creates a new array with the results of calling a function for each array element.
  • pop(): Removes the last element from an array, and returns that element.
  • push(): Adds one or more elements to the end of an array, and returns the array's new length.
  • reduce(): Reduce the values of an array to a single value (from left-to-right).
  • reduceRight(): Reduce the values of an array to a single value (from right-to-left).
  • reverse(): Reverses the order of the elements in an array.
  • shift(): Removes the first element from an array, and returns that element.
  • slice(): Selects a part of an array, and returns the new array.
  • some(): Checks if any of the elements in an array passes the test in a testing function.
  • sort(): Sorts the elements of an array.
  • splice(): Adds/Removes elements from an array.
  • toString(): Converts an array to a string, and returns the result.
  • unshift(): Adds new elements to the beginning of an array, and returns the array's new length.
  • values(): Returns a Array Iteration Object, containing the values of the original array.


Create New Methods

Prototype is a global constructor in JavaScript. It can construct new properties and methods for any JavaScript Objects.

Example: Make a new Array method.

 Array.prototype.ucase=function()
   {
       for (i=0;i       {
           this[i]=this[i].toUpperCase();
       }
   }

 

 Use:

   var LanguageName = ["Bangla"," English"," Spanish"];
   LanguageName.ucase();
   console.log(LanguageName);


 Output: ["BANGLA", " ENGLISH", " SPANISH"]


fruits[6] = "Lemon";                // adds a new element (Lemon) to fruits


The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes where objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.


When to Use Arrays. When to use Objects.

JavaScript does not support associative arrays.

You should use objects when you want the element names to be strings (text).

You should use arrays when you want the element names to be numbers.