ES6 - Arrays


Advertisements


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 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.

Features of an Array

  • An array declaration allocates sequential memory blocks.

  • Arrays are static. This means that an array once initialized cannot be resized.

  • Each memory block represents an array 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.

  • Array initialization refers to populating the array elements.

  • Array element values can be updated or modified but cannot be deleted.

Declaring and Initializing Arrays

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.

Initializing Arrays

Accessing Array Elements

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]

Example: Simple Array

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

Example: Single Statement Declaration and Initialization

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

Array Object

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 list of comma separated values.

The following Examples create an array using this method.

Example

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 

Example: Array Constructor Accepts Comma-separated Values

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

Array Methods

Following is the list of the methods of the Array object along with their description.

Sr.No Method & Description
1 concat()

Returns a new array comprised of this array joined with other array(s) and/or value(s)

2 every()

Returns true if every element in this array satisfies the provided testing function.

3 filter()

Creates a new array with all of the elements of this array for which the provided filtering function returns true.

4 forEach()

Calls a function for each element in the array.

5 indexOf()

Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.

6 join()

Joins all elements of an array into a string.

7 lastIndexOf()

Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.

8 map()

Creates a new array with the results of calling a provided function on every element in this array.

9 pop()

Removes the last element from an array and returns that element.

10 push()

Adds one or more elements to the end of an array and returns the new length of the array.

11 reduce()

Applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.

12 reduceRight()

Applies a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.

13 reverse()

Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.

14 shift()

Removes the first element from an array and returns that element slice.

15 slice()

Extracts a section of an array and returns a new array.

16 some()

Returns true if at least one element in this array satisfies the provided testing function.

17

toSource()

Represents the source code of an object.

18 sort()

Sorts the elements of an array.

19 splice()

Adds and/or removes elements from an array.

20 toString()

Returns a string representing the array and its elements.

21 unshift()

Adds one or more elements to the front of an array and returns the new length of the array.

ES6 − Array Methods

Following are some new array methods introduced in ES6.

Array.prototype.find

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.

Array.prototype.findIndex

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.

Array.prototype.entries

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

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.

  • 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

Array.prototype.keys()

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 ] 

Array Traversal using for…in loop

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

Arrays in JavaScript

JavaScript supports the following concepts about Arrays −

Sr.No Concept & Description
1 Multi-dimensional arrays

JavaScript supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array

2 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name without an index.

3 Return array from functions

Allows a function to return an array.

Array De-structuring

JavaScript supports de-structuring in the context of an array.

Example

var arr = [12,13] 
var[x,y] = arr 
console.log(x) 
console.log(y)

The following output is displayed on successful execution of the above code.

12 
13


Advertisements
E-Books Store