What is an Array?
The Array object is used to store multiple values in a single variable
const cars = ["car", "bus", "truck"];
Creating an Array
There are three ways to create an array:
Syntax:
const array_name = ["item1", "item2", "item3"];
const array_name = new Array("item1", "item2", "item3");
or
const array_name= [];
cars[0]= "item1";
cars[1]= "item2";
cars[2]= "item3";
Accessing Array Elements
const array_name = ["item1", "item2", "item3"];
let item= array_name[0];
console.log(item);
Let's talk about array methods:
- concat()
The concat() method concatenates two or more arrays.
The concat() method returns a new array, containing the joined arrays.
The concat() method does not change the existing arrays.
syntax
array1.concat(array2, array3, ..., arrayX)
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const children = arr1.concat(arr2);
- copyWithin()
The copyWithin() method copies array elements to another position in the array.
The copyWithin() method overwrites the existing values.
The copyWithin() method does not add items to the array.
**syntax**
array.copyWithin(target, start, end)
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.copyWithin(2, 0, 2);
- entries()
The entries() method returns an Array Iterator object with key/value pairs:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const f = fruits.entries();
[0, "Banana"]
[1, "Orange"]
[2, "Apple"]
[3, "Mango"]
The entries() method does not change the original array.
- every()
The every() method executes a function for each array element.
The every() method returns true if the function returns true for all elements.
The every() method returns false if the function returns false for one element.
The every() method does not execute the function for empty elements.
The every() method does not change the original array
syntax
array.every(function(currentValue, index, arr), thisValue)
Check if all values in ages[] are over 18:
const ages = [32, 33, 16, 40];
ages.every(checkAge)
function checkAge(age) {
return age > 18;
}
- fill()
The fill() method fills specified elements in an array with a value.
The fill() method overwrites the original array.
Start and end position can be specified. If not, all elements will be filled.
synatx
array.fill(value, start, end)
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.fill("Kiwi", 2, 4);
- filter()
The filter() method creates a new array filled with elements that pass a test provided by a function.
The filter() method does not execute the function for empty elements.
The filter() method does not change the original array.
syntax
array.filter(function(currentValue, index, arr), thisValue)
Return an array of all values in ages[] that are 18 or over:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
- find()
The find() method returns the value of the first element that passes a test.
The find() method executes a function for each array element.
The find() method returns undefined if no elements are found.
The find() method does not execute the function for empty elements.
The find() method does not change the original array.
syntax
array.find(function(currentValue, index, arr),thisValue)
Find the value of the first element with a value over 18:
const ages = [3, 10, 18, 20];
console.log(ages.find(checkAge));
function checkAge(age) {
return age > 18;
}
- findIndex()
The findIndex() method executes a function for each array element.
The findIndex() method returns the index (position) of the first element that passes a test.
The findIndex() method returns -1 if no match is found.
The findIndex() method does not execute the function for empty array elements.
The findIndex() method does not change the original array.
syntax
array.findIndex(function(currentValue, index, arr), thisValue)
const ages = [3, 10, 18, 20];
console.log(ages.findIndex(checkAge));
function checkAge(age) {
return age > 18;
}
- forEach()
The forEach() method calls a function for each element in an array.
The forEach() method is not executed for empty elements.
syntax
array.forEach(function(currentValue, index, arr), thisValue)
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction)
function myFunction(item, index) {
console.log(`${index}-${item}`);
}
- from()
The from() method returns an array from any object with a length property.
The from() method returns an array from any iterable object.
Create an array from a string:
Array.from("ABCDEFG")
- includes()
The includes() method returns true if an array contains a specified value.
The includes() method returns false if the value is not found.
The includes() method is case sensitive.
syntax
array.includes(element, start)
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Banana", 3);
- indexOf()
The indexOf() method returns the first index (position) of a specified value.
The indexOf() method returns -1 if the value is not found.
The indexOf() method starts at a specified index and searches from left to right.
By default the search starts at the first element and ends at the last.
Negative start values counts from the last element (but still searches from left to right).
syntax
array.indexOf(item, start)
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let index = fruits.indexOf("Apple");
- isArray()
The isArray() method returns true if an object is an array, otherwise false.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let result = Array.isArray(fruits);
- join()
The join() method returns an array as a string.
The join() method does not change the original array.
Any separator can be specified. The default is comma (,).
syntax
array.join(separator)
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = fruits.join(" and ");
- keys()
The keys() method returns an Array Iterator object with the keys of an array.
The keys() method does not change the original array.
syntax
array.keys()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
let text = "";
for (let x of keys) {
text += x + "<br>";
}
- lastIndexOf()
The lastIndexOf() method returns the last index (position) of a specified value.
The lastIndexOf() method returns -1 if the value is not found.
The lastIndexOf() starts at a specified index and searches from right to left.
By defalt the search starts at the last element and ends at the first.
Negative start values counts from the last element (but still searches from right to left).
syntax
array.lastIndexOf(item, start)
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let index = fruits.lastIndexOf("Apple");
- length The length property sets or returns the number of elements in an array.
syntax
array.length
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
- map()
map() creates a new array from calling a function for every array element.
map() calls a function once for each element in an array.
map() does not execute the function for empty elements.
map() does not change the original array.
syntax
array.map(function(currentValue, index, arr), thisValue)
Multiply all the values in an array with 10:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
- pop()
The pop() method removes (pops) the last element of an array.
The pop() method changes the original array.
The pop() method returns the removed element.
syntax
array.pop()
Remove (pop) the last element:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
- push()
The push() method adds new items to the end of an array.
The push() method changes the length of the array.
The push() method returns the new length.
syntax
array.push(item1, item2, ..., itemX)
Add a new item to an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
- reduce()
The reduce() method executes a reducer function for array element.
The reduce() method returns a single value: the function's accumulated result.
The reduce() method does not execute the function for empty array elements.
The reduce() method does not change the original array.
syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Subtract all numbers in an array:
const numbers = [175, 50, 25];
let num = numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
- reduceRight()
The reduceRight() method executes a reducer function for each array element.
The reduceRight() method works from right to left.
The reduceRight() method returns a single value: the function's accumulated result.
The reduceRight() method does not execute the function for empty elements.
syntax
array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
Subtract the numbers in the array, starting from the end:
const numbers = [175, 50, 25];
let num = numbers.reduceRight(myFunc);
function myFunc(total, num) {
return total - num;
}
- reverse()
The reverse() method reverses the order of the elements in an array.
The reverse() method overwrites the original array.
syntax
array.reverse()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
- shift()
The shift() method removes the first item of an array.
The shift() method changes the original array.
The shift() method returns the shifted element.
Shift (remove) the first element of the array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
- unshift()
The unshift() method adds new elements to the beginning of an array.
The unshift() method overwrites the original array.
Add new elements to an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
- sort()
The sort() sorts the elements of an array.
The sort() overwrites the original array.
The sort() sorts the elements as strings in alphabetical and ascending order.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
- splice()
The splice() method adds and/or removes array elements.
The splice() method overwrites the original array.
syntax
array.splice(index, howmany, item1, item2)
At position 2, remove 2 items:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.splice(2, 2);
At position 2, add 2 elements:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
- valueOf()
The valueOf() method returns the array itself.
The valueOf() method does not change the original array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const myArray = fruits.valueOf();