Table of contents
- What is an Array?
- Array
- How to declare arrays
- (1) Using array literals
- (2) Using javascript keyword new
- Acessing the array elements.
- What is the type of array
- Some common mistakes
- How to Recognize an Array
- Array methods :
- concat(): Joins arrays and returns an array with the joined arrays
- copyWithin():
- entries():
- every():
- fill():
- filter():
- find():
- findIndex():
- findLast() :
- forEach():
- from():
- includes():
- indexOf():
- Array.isArray()
- Array.join()
- Array.map()
- Array.of():
- Array.pop():
- Array.push()
- Array.reverse() :
- Array.shift()
- Array.slice()
- Array.sort()
- Array.splice():
- Array.toLocaleString():
- Array.prototype.toString():
- Array.prototype.unshift():
- Array.prototype.values():
- You have completed almost all the methods of array in javascript now you will be confident in array methods.
What is an Array?
An array is a collection of items which are stored at the contagious memory location .In javascript we can store items of different datatypes also in the same array. Items stored in the array can be accessed using the index of the respective element. Indexing in javascript starts from zero. If we want to access the first element of the array then we need to point at the 0th index of the array.
const cars = ["ferrari", "mercedes", "rover"];
Array
In JavaScript, arrays aren't primitives but are instead Array objects with the following core characteristics:
(1) JavaScript arrays are resizable and can contain a mix of different data types. (When those characteristics are undesirable, use typed arrays instead.)
(2) JavaScript arrays are not associative arrays so they must be positively indexed.
(3) JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.
(4) JavaScript array-copy operations create shallow copies. (All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies). It means they do not make changes in the original array.
How to declare arrays
(1) Using array literals
const names=["ram", "shyam" , "mohan"]
(2) Using javascript keyword new
const names=new Array["ram","shyam","mohan"]
There is no significant difference in keyword and literal declaration. The two examples above do exactly the same. For simplicity, readability and execution speed,we use the array literal method.
Acessing the array elements.
We can acess the array elements based on thier index.
const names=["ram", "shyam" , "mohan"];
console.log(names[0]);
console.log(names[1]);
console.log(names[2]);
OUTPUT ON CONSOLE: ram shyam mohan
If we want to iterate through all elements of the array we can also use loops for doing it.
const names=["ram", "shyam" , "mohan"];
for(i=0;i<names.length;i++){
console.log(names[i]);
}
const array= ['ram', 'shyam', 'mohan'];
for(let x in array){
console.log(array[x]);
}
const array= ['ram', 'shyam', 'mohan'];
for(let x of array){
console.log(x);
}
OUTPUT ON CONSOLE: ram shyam mohan
What is the type of array
const names=["ram", "shyam" , "mohan"];
console.log(typeof(names));
OUTPUT ON CONSOLE: object
Arrays are a special type of objects. typeof
operator returns object type for an array.JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array.
const names=[name1:"ram", name2:"shyam" ,name3: "mohan"];
console.log(names.name1);
OUTPUT ON CONSOLE: ram
Some common mistakes
var point1 = [40];
var point2=new Array(40);
var point3=new Array( 4,3);
console.log(point1.length);
console.log(point2.length);
console.log(point2.length);
OUTPUT ON CONSOLE: 1 , 40 , 2
Here we can see that for point1 we got output as 1 for length as 40 in point is treated as element while in point 2 when we directly passed as number it took it as the length of the array we are defining as we can see in the point3 when we passed two arguments then it returned 2 as result because now it started treating as an array.
How to Recognize an Array
As we read above that if we are going to check the type of array using typeof operator then it returns object so to overcome this problem in es5 a new method Array_Name.isArray(); was defined which returns true or false based on the condition that it is array or not.
const names=["ram", "shyam" , "mohan"];
console.log(names.isArray(names));
OUTPUT ON CONSOLE: true
Array methods :
concat(): Joins arrays and returns an array with the joined arrays
const names1=["ram", "shyam" , "mohan"];
const names2=["Bharat", "arjun" , "nakul"];
const all_names=names1.concat(names2);
console.log(all_names);
OUTPUT ON CONSOLE: ram, shyam , mohan, Bharat, arjun , nakul
Here we can see that names1 array has been concatenated with names2. Concatenation does not have any effect on the original array. We can also pass multiple array to the concat method like names1.concat(names2,names3,names4,.......)
.
copyWithin():
Copies array elements within the array, to and from specified positions
const array1 = ['a', 'b', 'c', 'd', 'e'];
// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]
// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]
copyWithin() method accepts three parameters:
copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
If negative indices are passed the this method then it is counted from backwards. In this method the original array gets modified and is returned by this method. It does not changes the length of the array.
Few more examples on copyWithin():
console.log([1, 2, 3, 4, 5].copyWithin(-2));
// [1, 2, 3, 1, 2]
console.log([1, 2, 3, 4, 5].copyWithin(0, 3));
// [4, 5, 3, 4, 5]
console.log([1, 2, 3, 4, 5].copyWithin(0, 3, 4));
// [4, 2, 3, 4, 5]
console.log([1, 2, 3, 4, 5].copyWithin(-2, -3, -1));
// [1, 2, 3, 3, 4]
entries():
The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.
const array = ["abhay", "billu", "akash"];
const arrayEntries = array.entries();
for (const element of arrayEntries) {
console.log(element);
}
// [0, 'abhay']
// [1, 'billu']
// [2, 'akash']
every():
Checks if every element in an array pass a test
const isgreater = (currentVal) => currentVal< 40;
const array1 = [1, 30, 29, 35, 11, 13];
console.log(array1.every(isgreater));
// Expected output: true
Following example tests whether all the elements in the given array are less than 40 or not.
fill():
Fill the elements in an array with a static value. The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.
const array1 = [1, 2, 3, 4];
// Fill with 5 from position 2 until position 4
console.log(array1.fill(5, 2, 4));
// Expected output: Array [1, 2, 5, 5]
// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]
console.log(array1.fill(9));
// Expected output: Array [9, 9, 9, 9]
fill method accepts three parameters and these are value, start and end. fill(value)
fill(value, start)
fill(value, start, end)
The fill() method is a mutating method. It does not alter the length of this, but it will change the content of this.
More Examples on fill() method:
console.log([1, 2, 3].fill(4)); // [4, 4, 4]
console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4]
console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3]
console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3]
console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3]
console.log(Array(3).fill(4)); // [4, 4, 4]
// A single object, referenced by each slot of the array:
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
filter():
Creates a new array with every element in an array that pass a test. This method creates a new array which is shallow copy of a portion of the original array which is filtered down to the elements from the given array that pass a given condition implemented by a function.
const words = ['Newyork', 'Speed', 'referenced', 'method', 'portion'];
const result = words.filter(word => word.length >= 6);
console.log(result);
// expected result [ 'Newyork','referenced', 'method', 'portion'];
find():
Returns the value of the first element in an array that pass a test and if the element is not found then it returns undefined.
const array=[1,2,3,4,5,6,7,9];
console.log(array.find(element=>element>5));
// Expected Output: 6, 7, 9
findIndex():
Returns the index of the first element in an array that pass a test and If no elements satisfy the testing function, -1 is returned.
const array=[1,2,3,4,5,6,7,9];
const isLargeNumber = (element) => element > 3;
console.log(array.findIndex(isLargeNumber));
// Expected output: 3
findLast() :
The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
const array=[1,2,3,4,5,6,7,9];
const isLargeNumber = (element) => element > 3;
console.log(array.findIndex(isLargeNumber));
// Expected output: 7
forEach():
Calls a function for each array element.it can be used to iterate over the elements also.
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
forEach() method can also be used as a for loop
const items = ["item1", "item2", "item3"];
const copyItems = [];
// before
for (let i = 0; i < items.length; i++) {
copyItems.push(items[i]);
}
// after
items.forEach((item) => {
copyItems.push(item);
});
from():
Creates an array from an object.The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// Expected output: Array [2, 4, 6]
Array.from("foo");
// [ "f", "o", "o" ]
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]
includes():
Check if an array contains the specified element.The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const array1 = [3, 2,4, 7];
console.log(array1.includes(2));
// Expected output: true
const pronoun = ['me', 'you', 'us'];
console.log(pronoun.includes('us'));
// Expected output: true
console.log(pronoun.includes('at'));
// Expected output: false
indexOf():
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.Search the array for an element and returns its position.
const array1 = [3, 2,4, 3];
console.log(array1.indexof(2));
// Expected output: 1
const pronoun = ['me', 'you', 'us'];
console.log(pronoun.includes('us'));
// Expected output: 2
// Start from index 2
console.log(array.indexOf(3, 2));
// Expected output: 3
// here the searching will start from 2nd index of the array.
Array.isArray()
The Array.isArray() static method determines whether the passed value is an Array.
console.log(Array.isArray([3, 6, 5]));
// Expected output: true
console.log(Array.isArray('[]'));
// Expected output: false
console.log(Array.isArray(new Array(5)));
// Expected output: true
Some of the more examples.
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
// This is not an array, because it was not created using the
// array literal syntax or the Array constructor
Array.isArray({ __proto__: Array.prototype });
Array.join()
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const pro = ['me', 'you', 'us'];
console.log(pro.join());
// Expected output: 'me, you, us'
console.log(pro.join(''));
// Expected output: 'me you us'
console.log(pro.join('-'));
// Expected output:'me-you-us'
Array.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array= [3, 2, 4, 1, 6];
const array1=array.map(x=>x+2);
console.log(array1);
//Expected output: [5, 4, 6, 3, 8]
Array.of():
The Array.of() static method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.
const array= Array.of(3, 2, 4, 1, 6,"name");
// Expected output: [3, 2, 4, 1, 6,"name"]
Array.of(7); // [7]
Array(7); // array of 7 empty slots
Array.of(3);
//Expected output: array of 3 empty slots
Array(1, 2, 3);
//Expected output: [1, 2, 3]
Array.pop():
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
const array= [3, 2, 4, 1, 6]
console.log(array);
//Expected output: [3, 2, 4, 1, 6]
console.log(array.pop());
//Expected output: 6
console.log(array);
//Expected output: [3, 2, 4, 1]
Array.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
const array= [3, 2, 4, 1, 6]
console.log(array);
//Expected output: [3, 2, 4, 1, 6]
console.log(array.push(9));
//Expected output: 6 it is the new length of the array
console.log(array);
//Expected output: [3, 2, 4, 1, 6, 9]
Array.reverse() :
The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
const array= [3, 2, 4, 1, 6]
console.log(array);
//Expected output: [3, 2, 4, 1, 6]
console.log(array.reverse());
console.log(array);
//Expected output: [6,1,4,2,3]
// beware the reverse() method changes the original rray
Array.shift()
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
const array= [3, 2, 4, 1, 6]
console.log(array);
//Expected output: [3, 2, 4, 1, 6]
console.log(array.shift());
// Expected output: 3
console.log(array);
//Expected output: [2, 4, 1, 6]
// Beware, shift() method changes the original array length
Array.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. This method accepts two parameters start and end.
//array.slice(start, end)
const array= [3, 2, 4, 1, 6]
console.log(array);
//Expected output: [3, 2, 4, 1, 6]
console.log(array.slice(2,4));
console.log(array);
// Expected output: [4,1]
console.log(array.slice(2));
console.log(array);
// Expected output: [4,1,6]
Array.some() The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
const array = [1, 2, 3, 4, 5];
// Checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// Expected output: true
Array.sort()
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 3, 4, 21, 0];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]
By default, the sort method sorts an array as strings.
This is fine in case of strings that are sorted alphabetically, but it produces incorrect results when we sort numbers. We can fix it by passing the compare function to the sort method
const numbers = [100, 25, 1, 5];
const sorted = numbers.slice().sort(function(a, b) {
return a - b;
}); // returns a new sorted array
console.log(numbers); // [100, 25, 1, 5]
console.log(sorted); // [1, 5, 25, 100]
When comparing 100 and 25, the sort() method calculates 100 - 25 as 75 which is a positive value so it puts 25 before 100.
This will sort the array in ascending order.
Array.splice():
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
Array.toLocaleString():
The toLocaleString() method returns a string representing the elements of the array. The elements are converted to Strings using their toLocaleString methods and these Strings are separated by a locale-specific String (such as a comma ",").
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);
// Expected output: "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
Array.prototype.toString():
The toString() method returns a string representing the specified array and its elements.
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// Expected output: "1,2,a,1a"
Array.prototype.unshift():
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// Expected output: 5
console.log(array1);
// Expected output: Array [4, 5, 1, 2, 3]
Array.prototype.values():
The values() method returns a new array iterator object that iterates the value of each item in the array.
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"