- ES6 - Discussion
- ES6 - Useful Resources
- ES6 - Quick Guide
- ES9 - New Features
- ES8 - New Features
- ES7 - New Features
- ES6 - Browsers
- ES6 - Image Map
- ES6 - Debugging
- ES6 - Multimedia
- ES6 - Animation
- ES6 - Validations
- ES6 - Proxy API
- ES6 - Reflect API
- ES6 - Object Extensions
- ES6 - Error Handling
- ES6 - Modules
- ES6 - Promises
- ES6 - Maps And Sets
- ES6 - Classes
- ES6 - Collections
- ES6 - Iterator
- ES6 - HTML DOM
- ES6 - RegExp
- ES6 - Math
- ES6 - Date
- ES6 - Arrays
- ES6 - New String Methods
- ES6 - Symbol
- ES6 - Strings
- ES6 - Boolean
- ES6 - Number
- ES6 - Objects
- ES6 - Page Printing
- ES6 - Void Keyword
- ES6 - Dialog Boxes
- ES6 - Page Redirect
- ES6 - Cookies
- ES6 - Events
- ES6 - Functions
- ES6 - Loops
- ES6 - Decision Making
- ES6 - Operators
- ES6 - Variables
- ES6 - Syntax
- ES6 - Environment
- ES6 - Overview
- ES6 - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
ES6 - Arrays
The use of variables to store values poses the following pmitations −
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 simppfy, 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 initiapzed 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, pke variables, should be declared before they are used.
Array initiapzation refers to populating the array elements.
Array element values can be updated or modified but cannot be deleted.
Declaring and Initiapzing Arrays
To declare and initiapze an array in JavaScript use the following syntax −
var array_name; //declaration array_name = [val1,val2,valn..] //initiapzation OR var array_name = [val1,val2…valn]
Note − The pair of [] is called the dimension of the array.
For example, a declaration pke: var numpst = [2,4,6,8] will create an array as shown in the following figure.
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 Initiapzation
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 pst 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 pst of the methods of the Array object along with their description.
Sr.No | Method & Description |
---|---|
1 |
Returns a new array comprised of this array joined with other array(s) and/or value(s) |
2 |
Returns true if every element in this array satisfies the provided testing function. |
3 |
Creates a new array with all of the elements of this array for which the provided filtering function returns true. |
4 |
Calls a function for each element in the array. |
5 |
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. |
6 |
Joins all elements of an array into a string. |
7 |
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. |
8 |
Creates a new array with the results of calpng a provided function on every element in this array. |
9 |
Removes the last element from an array and returns that element. |
10 |
Adds one or more elements to the end of an array and returns the new length of the array. |
11 |
Apppes a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. |
12 |
Apppes a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. |
13 |
Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. |
14 |
Removes the first element from an array and returns that element spce. |
15 |
Extracts a section of an array and returns a new array. |
16 |
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 |
Sorts the elements of an array. |
19 |
Adds and/or removes elements from an array. |
20 |
Returns a string representing the array and its elements. |
21 |
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 pke object. The basic functionapty of Array.from() is to convert two kinds of values to Arrays −
Array-pke values.
Iterable values pke 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 |
JavaScript supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array |
2 |
You can pass to the function a pointer to an array by specifying the array s name without an index. |
3 |
Allows a function to return an array. |
Array De-structuring
Destructuring refers to extracting inspanidual values from an array or an object into distinct variables. Consider a scenario where the values of an array need to be assigned to inspanidual 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.
Syntax
//destructuring an array let [variable1,variable2]=[item1,item2] //destructuring an object let {property1,property2} = {property1:value1,property2:value2}
Example
<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 20Advertisements