ES6 - Arrays

The use of variables to store values poses the following limitations −
Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program, n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.
Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.
JavaScript introduces the concept of arrays to tackle the same.
An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user-defined type.
An array declaration allocates sequential memory blocks.
An array declaration allocates sequential memory blocks.
Arrays are static. This means that an array once initialized cannot be resized.
Arrays are static. This means that an array once initialized cannot be resized.
Each memory block represents an array element.
Each memory block represents an array element.
Array elements are identified by a unique integer called as the subscript/index of the element.
Array elements are identified by a unique integer called as the subscript/index of the element.
Arrays too, like variables, should be declared before they are used.
Arrays too, like variables, should be declared before they are used.
Array initialization refers to populating the array elements.
Array initialization refers to populating the array elements.
Array element values can be updated or modified but cannot be deleted.
Array element values can be updated or modified but cannot be deleted.
To declare and initialize an array in JavaScript use the following syntax −
var array_name; //declaration 
array_name = [val1,val2,valn..]   //initialization 
OR 
var array_name = [val1,val2...valn]

Note − The pair of [] is called the dimension of the array.
For example, a declaration like: var numlist = [2,4,6,8] will create an array as shown in the following figure.
The array name followed by the subscript is used to refer to an array element.
Following is the syntax for the same.
array_name[subscript]

var alphas; 
alphas = ["1","2","3","4"] 
console.log(alphas[0]); 
console.log(alphas[1]);
The following output is displayed on successful execution of the above code.
1 
2

var nums = [1,2,3,3] 
console.log(nums[0]); 
console.log(nums[1]); 
console.log(nums[2]); 
console.log(nums[3]);
The following output is displayed on successful execution of the above code.
1 
2 
3 
3

An array can also be created using the Array object. The Array constructor can be passed as −
A numeric value that represents the size of the array or.
A numeric value that represents the size of the array or.
A list of comma separated values.
A list of comma separated values.
The following Examples create an array using this method.
var arr_names = new Array(4)  
for(var i = 0;i<arr_names.length;i++) { 
   arr_names[i] = i * 2 
   console.log(arr_names[i]) 
}
The following output is displayed on successful execution of the above code.
0 
2 
4 
6 

var names = new Array("Mary","Tom","Jack","Jill") 
for(var i = 0;i<names.length;i++) { 
   console.log(names[i]) 
}
The following output is displayed on successful execution of the above code.
Mary 
Tom 
Jack 
Jill

Following is the list of the methods of the Array object along with their description.
Returns a new array comprised of this array joined with other array(s) and/or value(s)
Returns true if every element in this array satisfies the provided testing function.
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
Calls a function for each element in the array.
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
Joins all elements of an array into a string.
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
Creates a new array with the results of calling a provided function on every element in this array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array and returns the new length of the array.
Applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
Applies a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.
Removes the first element from an array and returns that element slice.
Extracts a section of an array and returns a new array.
Returns true if at least one element in this array satisfies the provided testing function.
toSource()
Represents the source code of an object.
Sorts the elements of an array.
Adds and/or removes elements from an array.
Returns a string representing the array and its elements.
Adds one or more elements to the front of an array and returns the new length of the array.
Following are some new array methods introduced in ES6.
find lets you iterate through an array and get the first element back that causes the given callback function to return true. Once an element has been found, the function immediately returns. It’s an efficient way to get at just the first item that matches a given condition.
Example
var numbers = [1, 2, 3]; 
var oddNumber = numbers.find((x) => x % 2 == 1); 
console.log(oddNumber); // 1
The following output is displayed on successful execution of the above code.
1

Note − The ES5 filter() and the ES6 find() are not synonymous. Filter always returns an array of matches (and will return multiple matches), find always returns the actual element.
findIndex behaves similar to find, but instead of returning the element that matched, it returns the index of that element.
var numbers = [1, 2, 3]; 
var oddNumber = numbers.findIndex((x) => x % 2 == 1); 
console.log(oddNumber); // 0 
The above example will return the index of the value 1 (0) as output.
entries is a function that returns an Array Iterator that can be used to loop through the array’s keys and values. Entries will return an array of arrays, where each child array is an array of [index, value].
var numbers = [1, 2, 3]; 
var val = numbers.entries(); 
console.log(val.next().value);  
console.log(val.next().value);  
console.log(val.next().value);
The following output is displayed on successful execution of the above code.
[0,1] 
[1.2] 
[2,3]

Alternatively, we can also use the spread operator to get back an array of the entries in one go.
var numbers = [1, 2, 3]; 
var val= numbers.entries(); 
console.log([...val]);

The following output is displayed on successful execution of the above code.
[[0,1],[1,2],[2,3]]

Array.from() enables the creation of a new array from an array like object. The basic functionality of Array.from() is to convert two kinds of values to Arrays −
Array-like values.
Array-like values.
Iterable values like Set and Map.
Iterable values like Set and Map.
Example
"use strict" 
for (let i of Array.from('hello')) { 
   console.log(i) 
}
The following output is displayed on successful execution of the above code.
h                               
e                               
l                               
l                               
o

This function returns the array indexes.
Example
console.log(Array.from(['a', 'b'].keys()))
The following output is displayed on successful execution of the above code.
[ 0, 1 ] 

One can use the for... in loop to traverse through an array.
"use strict" 
var nums = [1001,1002,1003,1004] 
for(let j in nums) { 
   console.log(nums[j]) 
}
The loop performs an index-based array traversal. The following output is displayed on successful execution of the above code.
1001 
1002 
1003 
1004

JavaScript supports the following concepts about Arrays −
JavaScript supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array
You can pass to the function a pointer to an array by specifying the array's name without an index.
Allows a function to return an array.
Destructuring refers to extracting individual values from an array or an object into distinct variables. Consider a scenario where the values of an array need to be assigned to individual variables. The traditional way of doing this is given below −
var a= array1[0]
var b= array1[1]
var c= array1[2]

Destructuring helps to achieve the same in a concise way.
//destructuring an array
let [variable1,variable2]=[item1,item2]
//destructuring an object
let {property1,property2} = {property1:value1,property2:value2}

<script>
   let names = ['Mohtashim','Kannan','Kiran']
   let [n1,n2,n3] = names;
   console.log(n1)
   console.log(n2)
   console.log(n3);
   //rest operator with array destructuring
   let locations=['Mumbai','Hyderabad','Chennai']
   let [l1,...otherValues] =locations
   console.log(l1)
   console.log(otherValues)
   //variables already declared
   let name1,name2;
   [name1,name2] =names
   console.log(name1)
   console.log(name2)
   //swapping
   let first=10,second=20;
   [second,first] = [first,second]
   console.log("second is ",second) //10
   console.log("first is ",first) //20
</script>
The output of the above code will be as shown below −
Mohtashim
Kannan
Kiran
Mumbai
["Hyderabad", "Chennai"]
Mohtashim
Kannan
second is 10
first is 20


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page