Sam  Son

How is the Arrays in JavaScript?

In JavaScriptarray is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. It’s a more convenient way to store and structure information than is defining of lots of variables with slightly different names, like this:

var fruit0 = 'Mango';
var fruit1 = 'Apple';
var fruit2 = 'Orange';

Instead of the above, we can use array to structure the data like this:

Var fruits = new Array('Mango','Apple','Orange');

Declaration of an Array

There are basically two ways to declare an array.

With the literal notation []

var array = [1, 2, 3]

With the Array() constructor

var array = new Array(1, 2, 3)

Basically both the approaches are same but most of the people use literal notation as it’s quicker to type and less code-intensive.

Arrays can be anything — numbers, strings, functions even other arrays and within the arrays you can mix different type of data freely.

var number = [1, 2, 3, 4, 5]
var strings = ['name', 'place', 'food' ]
var functions = [ function x(){...}, finction y(){...} ]
var mix = [ 12, 'niceplace', function xy(){...} ]

Accessing values of arrays.

We can access the values of an array by referring to an index number. Index number can be define as the location of an item in array. To get the value we refer to the members of an array using the index number in a square bracket [].

For example :

var array = [ 'val1', 'val2', 'val3']
alert(array[0]); // alerts val1.

note : indexing of arrays starts from 0 in the above example you can see array[0] alerts the first value of the array while array[1] will alert the 2nd value. To check this you can define an array and use console.table to see the indexing of the array.

Creating an Array of Arrays

An array of arrays is known as multi-dimensional array or matrix. These are constructed like this :

var Avengers = [
    [ 'ironman', 'dr.strange', 'cap.america' ],
    [ 'blackwidow', 'scarletwitch', 'wasp' ]
];

You can also construct a multi-dimensional array using Array() constructor like this :

var Avengers = new Array(
   new Array('ironman', 'dr.strange', 'cap.america'),
   new Array('blackwidow', 'scarletwitch', 'wasp')
);

Items in a multi-dimensional array are addressed in the same way as single arrays, but for the difference we address each item using multiple values, starting from the outermost array. For example, the value of wasp is located at index of 1 of the outermost array, and index 2 of the nested array, so we would refer to it as Avengers[1][2].

For better understanding consider this table :

Indexing an Array with Strings Instead of Numbers

We can index an array using strings, instead of numbers. This is often useful when we use multi-dimensional arrays to group related data.

We can’ t directly put together an array with string indexes and populate it, for this we have to first create an empty array and then index and populate it.

var Avengers = [];
Avengers['males'] = [ 'ironman', 'dr.strange', 'cap.america' ];
Avengers['females'] = [ 'blackwidow', 'scarletwitch', 'wasp' ];

Now, we can reference ‘ironman’ as Avengers[‘males’][0], and ‘scarletwitch’ as Avengers[‘females’][1].

Turning an Array into a String.

JavaScript provides a number of methods for processing arrays. One of the most useful is the ability to turn an array into a string.

By join() method

The join method concatenates all the members of an array into a string, along with a separator. If the separator argument is omitted, a comma is used by default:

var Avengers = [ 'ironman', 'dr.strange', 'cap.america' ];
var together = Avengers.join('');
alert(together); 
var list = Avengers.join();
alert(list);
var sentence = Avengers.join(' and ')
alert(sentence);

Now, together is ‘ironmandr.strangecap.america’, list is ‘ironman,dr.strange,cap.america’ and sentence is ‘ironman and dr.strange and cap.america’.

By toString() method

You can also convert the Array into a string by the toString() method.

var Avengers = [ 'ironman', 'dr.strange', 'cap.america' ];
var together = Avengers.toString();
alert(together); // ironman,dr.strange,cap.america

toString method also works the same way as the join() method do but unlike join() which can join an array together by a separator, toString() method join an array by comma separated only.

Adding or Removing Members from an Array

To modify or delete data from an array you must know how to add or remove members from an array. JavaScript provides various methods to add, remove or change data of an array. Some of the methods do the same task but have different approach.

Changing/Replacing an existing value with a new one.

So now, you created an array and for some reason you want change a specific value of an array. This can be done by the assignment operator.

var Coffee = ['Americano', 'Cappuccino', 'Expresso', 'Latte'];
Coffee[0] = 'Mocha';
alert(Coffee);

Now, Coffee is Mocha,Cappuccino,Expresso,Latte.

Well this method can be useful to change a specific value but let say you by mistake give reference to an index number which doesn’t have any value contain any value. In that case JavaScript just adds the value you assigned to that index. For example

var Coffee = ['Americano', 'Cappuccino', 'Expresso', 'Latte'];
Coffee[4] = "Macchiato";
alert(Coffee);

Macchiato will be added to the array at index 4.

Now Cofffee is Mocha,Cappuccino,Expresso,Latte,Macchiato

But this way of adding items in an array is not a good practice. Consider the given example

var Coffee = ['Americano', 'Cappuccino', 'Expresso', 'Latte'];
Coffee[5] = "Macchiato";
alert(Coffee);

In this you can see we have 4 item in the array and the last index is 3. Instead of referring 4th index to assign the value, we referred to the 5th one. This will create an empty or null value between the 3rd and 5th index.

empty value at index 4.

So to add or remove values without any issue, JavaScript provide various method to work upon and ease our work.

Adding Members : The push() and unshift() method

The unshift() method adds new items to the beginning of an array, and returns the new length.

var DBZ = ['Goku', 'Vegita', 'Gohan', 'Goten'];
DBZ.unshift("Frieza");
alert(DBZ);

DBZ will now be Frieza,Goku,Vegita,Gohan,Goten.

The push() method appends the given element(s) in the last of the array and returns the length of the new array.

var DBZ = ['Goku', 'Vegita', 'Gohan', 'Goten'];
DBZ.push("Trunks");
alert(dbz);

DBZ will now be Goku,Vegita,Gohan,Goten,Trunks

Removing Members : The pop() and shift() method

Like push() and unshift() JavaScript provides two useful methods to remove an item from the beginning and the end.

The shift() method removes a first item from an array and returns that removed element. This method changes the length of the array on which we are calling the shift() method.

var Naruto = ['Naruto', 'Sasuke', 'Sakura', ' Hinata'];
Naruto.shift();
alert(Naruto);

Now Naruto will be Sasuke,Sakura, Hinata

The pop() method removes a last element of an array and returns that element.

var Naruto = ['Naruto', 'Sasuke', 'Sakura', ' Hinata'];
Naruto.pop();
alert(Naruto);

Now Naruto will be Naruto,Sasuke,Sakura

Understanding splice() and slice() methods

Now we know how to add/remove an item from an array from the beginning or end. It’s time to understand how you can add or remove item from between the elements of an array.


The splice() method is an inbuilt method in JavaScript which is used to modify the contents of an array by removing the existing elements and/or by adding new elements.

Syntax:

Array.splice( index, remove_count, item_list )

. index : Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.

. remove_count : Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.

. item_list : Optional. The new item(s) to be added to the array.

var Pokemon = [ 'Pikachu', 'Bulbasaur', 'Charmander', 'Squirtle', 'Caterpie' ];
Pokemon.splice(2); // remove ["Charmander", "Squirtle", "Caterpie"]
alert(Pokemon); // Pikachu,Bulbasaur

Let’s remove ‘.Charmander’ from the list.

var Pokemon = [ 'Pikachu', 'Bulbasaur', 'Charmander', 'Squirtle', 'Caterpie' ];
Pokemon.splice(2,1);
alert(Pokemon); // Pikachu,Bulbasaur,Squirtle,Caterpie

Let’s add ‘Evolve’ between ‘Bulbasaur’ and ‘Charmander’

var Pokemon = [ 'Pikachu', 'Bulbasaur', 'Charmander', 'Squirtle', 'Caterpie' ];
Pokemon.splice(2,0,'Evolve');
alert(Pokemon);  
// Pikachu,Bulbasaur,Evolve,Charmander,Squirtle,Caterpie

The slice() method returns the selected elements in an array, as a new arrayobject. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

Syntax :

Array.slice(start, end)

. start : An integer that specifies where to start the selection. Use negative numbers to select from the end of an array.

. end : An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.

var life = ['eat', 'sleep', 'code', 'repeat'];
var slice = life.slice(2);
alert(slice); // code,repeat
alert(life) // eat,sleep,code,repeat 

Original array will remain intact.

Now let’s remove ‘eat’ and ‘repeat’ item from the array.

var life = ['eat', 'sleep', 'code', 'repeat'];
var slice = life.slice(1,3);
alert(slice) // sleep,code

You can also check whether the item you selected is present in the array or not by includes() method which will give either true or false depending upon the item present or not in the list respectively.

checking presence of item in an array by includes() method

Sorting an Array into Alphabetical or Numerical Order

Sorting by letter or number allows you to order data by particular criteria. You could order names alphabetically, or phone numbers by area code etc.

The sort() method will sort an array into alphabetical order.

var songs = [’Voices’, ’Wasteland’, ’Gravity’, 'Scream’, 'Runaway’];
songs.sort();
alert(songs);

Now the sorted array will be Gravity,Runaway,Scream,Voices,Wasteland

To sort numeric values, we can’t use sort() method directly. For numeric sort we have to write an additional function :

var score = [25, 8, 5, 2, 4, 1, 7, 1995];
score.sort(function(a,b){
return a-b } 
);

Sorted array will now be 1, 2, 4, 5, 7, 8, 25, 1995.

Reversing an Array

JavaScript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first.

Syntax :

Array.reverse();

Examples :

var Avengers = [
    [ 'ironman', 'dr.strange', 'cap.america' ],
    [ 'blackwidow', 'scarletwitch', 'wasp' ]
];
Avengers.reverse();
alert(Avengers); 
// blackwidow,scarletwitch,wasp,ironman,dr.strange,cap.america

See here not only the inner elements but the outer elemens are also reversed.

For better understanding consider this table :

original Array

Array after reversing.

Thanks for reading!

#javascript #java

How is the Arrays in JavaScript?
2 Likes14.40 GEEK