Javascript array can store multiple elements of different data types.
Array Methods :
===============
1.push() - Adds one or more elements at the end of an array and returns new length of the array.
ex :
let stocks =[{type:"Apple",year:1975}];
stocks.push({type:"Microsoft",year:1976});
stocks.push({type:"Amazon",year:1995},{type:"salesforce",year:2003});
console.log(stocks) // [{type:"Apple",year:1975},{type:"Microsoft",year:1976},{type:"Amazon",year:1995},{type:"salesforce",year:2003}]
Note : push() appends elements to the end of the given array.
2.pop() - Removes the last element from an array and returns that element.
ex :
let stocks =[
{type:"Apple",year:1975},
{type:"Microsoft",year:1976},
{type:"Amazon",year:1995}
];
poppedStock=stocks.pop();
console.log(stocks) // [{type:"Apple",year:1975},{type:"Microsoft",year:1976}]
console.log(poppedStock); // {type:"Amazon",year:1995}
3.shift() - Removes the first element and return that element.
ex :
let stocks =[
{type:"Apple",year:1975},
{type:"Microsoft",year:1976},
{type:"Amazon",year:1995}
];
shiftedStock=stocks.shift();
console.log(stocks) // [{type:"Microsoft",year:1976},{type:"Amazon",year:1995}]
console.log(shiftedStock); // {type:"Apple",year:1975}
4.unshift() - Adds the element to the beginning of an array and return new array length.
ex :
let stocks =[
{type:"Apple",year:1975},
{type:"Microsoft",year:1976},
{type:"Amazon",year:1995}
];
let newstock={type:"salesforce",year:2003};
unshiftedStock=stocks.unshift(newstock);
console.log(stocks) // [{type:"salesforce",year:2003},{type:"Apple",year:1975},{type:"Microsoft",year:1976},{type:"Amazon",year:1995}]
console.log(unshiftedStock); // 4
5.reverse() - Reverse the elements of an array.
ex :
let stocks =[
{type:"Apple",year:1975},
{type:"Microsoft",year:1976},
{type:"Amazon",year:1995}
];
stocks.reverse();
console.log(stocks) // [{type: "Amazon", year: 1995},{type:"Microsoft",year:1976},{type:"Apple",year:1975}]
6.splice - adds and remove elements from an array.
synatx :
array.splice(start,end) // to remove elements
array.splice(start,0,element1,element2,....) // to add elements.
ex : delete element from an array
let stocks =[
{type:"Apple",year:1975},
{type:"Microsoft",year:1976},
{type:"Amazon",year:1995},
{type:"Salesforce",year:2003}
];
deletedStocks = stocks.splice(0,3);
console.log(stocks) // [{type:"Salesforce",year:2003}];
console.log(deletedStocks) // [{type:"Apple",year:1975},{type:"Microsoft",year:1976},{type:"Amazon",year:1995}];
ex : add element to an array
let stocks =[
{type:"Apple",year:1975},
{type:"Amazon",year:1995},
{type:"Salesforce",year:2003}
];
stocks.splice(1,0,{type:"Microsoft",year:1976});
console.log(stocks) // [{type:"Apple",year:1975},{type:"Microsoft",year:1976},{type:"Amazon",year:1995},{type:"Salesforce",year:2003}];
Note : The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements,
in the original array.
7.indexOf() - Returns the index of the first occurrence of the specified element in the array,or -1 if it is not found.
ex : let fruits = ["Banana", "Orange", "Apple", "Mango"];
let IndexedFruit = fruits.indexOf("Apple");
console.log(IndexedFruit) // 2
Note :
indexOf() expects a value as first parameter. This makes it a good choice to find the index in arrays of primitive types (like string,boolean,number).
findIndex() expects a callback as first parameter.Use this if you need the index in arrays with non-primitive types (e.g. objects) or your find condition
is more complex than just a value.
ex : let stocks =[
{type:"Apple",year:1975},
{type:"Amazon",year:1995},
{type:"Salesforce",year:2003}
];
let indexedStock =stocks.findIndex( x => x.type ==="Salesforce");
console.log(indexedStock) //2
findIndex() return the index of the first element in the array that satisfies the condition.
if the condition is not satisfied,-1 is returned.
8.lastIndexOf - Returns the index of the last occurrence of the specified element in the array,
or -1 if it is not found.
ex :
let fruits = ["Apple","Banana", "Orange", "Apple", "Mango"];
let lastIndexedFruit = fruits.lastIndexOf("Apple");
console.log(lastIndexedFruit) // 3
9.join() - Returns string of all the elements separated by the specified separator.
The join() method joins all elements of an array into a string.
ex :
let alphabets =["A","B","C","D"];
let result = alphabets.join();
console.log(result); // A,B,C,D
Note : It accepts a "separator" as argument, but the default is already a comma (,).
str =arr.join([separator=',']);
10. slice() - Returns a new array with specified start to end elements.
The slice() method copies a given part of an array and returns that copied part
as a new array.it doesn't change the original array.
synatx :
array.slice(from,until);
ex :
let alphabets =["A","B","C","D"];
let result = alphabets.slice(1,3);
console.log(result); // ["B","C"]
11. contact() - Returns new array by combining values of an array that is
specified as parameter with existing array values.
The contact() method is used to merge two or more arrays.
This method does not change the existing arrays, but instead returns a new array.
ex :
let array1=[1,2,3,4,5];
let array2=[6,7,8,9,10];
let array3=array1.contact(array2);
or
let array3=[].contact(array1,array2);
console.log(array3); // [1,2,3,4,5,6,7,8,9,10]
12. map() - loop over the array and return new array based on the value return.
ex :
let stocks =[
{type:"Apple",year:1975},
{type:"Amazon",year:1995},
{type:"Salesforce",year:2003}
];
let names=stocks.map(x => { return x.type });
console.log(names) // ["Apple","Amazon","Salesforce"]
Array.prototype.map(callback,thisValue);
The map function have three arguments for the callback(currentValue,index,array).
currentValue : required,the current element being processed in the array.
index : Optional, the index of the current element being processed in the array.
array : Optional, the array map was called upon.
And "thisValue" is to use this when executing callback.
ex : let names=stocks.map((item,index) => {return item.type+index});
console.log(names) // ["Apple0", "Amazon1", "Salesforce2"]
ex :
const myArray = [1, 2, 3];
// using the third argument to map
myArray.map((value, index, array) => {
return array[index] + 1;
});
// [2,3,4]
A this value is a special object which is related with the execution context of the function.
ex :
let myObject = { name: 'myObject' };
[1,2].map(function(item) {
console.log(item); // 1, 2
console.log(this === myObject); // true
}, myObject)
13. every() - return true or false if every element in the array satisfy the condition.
Checks if all elements of the array satisfies the provided callback function.
ex : let array =[0,2,4,6];
let result =array.every (item => (item % 2 ===0));
console.log(result) // true
Note : if all elements return true, then every() will return true.
ex : For Empty Arrays
let nums = [];
let result = (nums.length) ? nums.every(n => n==5) : false;
14. reduce() - This method reduces the array to a single value(left to right).
returns a callback for each element of an array.
reduce passes the result of this callback(the accumulator) from one array element to the other.
The accumulator can be pretty much anything (integer,string,object,etc) and must be instantiated
or passed when calling .reduce().
The reduce function takes four arguments.
1.Accumulator
2.Current Value
3.Current Index
4.Source Array
The reduce function returned value is assigned to the accumulator,
whose value is remembered across each iteration throughout the array
and ultimately becomes the final single resulting value.
ex :
let pilots = [
{ id: 10,name: "Poe Dameron",years: 14},
{ id: 20,name: "Temmin",years: 30},
{ id: 41,name: "Tallissan Lintra",years: 16},
{ id: 99,name: "Ello Asty",years: 22}
];
let totalYears = pilots.reduce((accumulator, pilot) =>
accumulator + pilot.years ,0);
console.log(totalYears) // 82
ex :
get most experienced pilot
let mostExpPilot = pilots.reduce((oldest, pilot) => {
return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});
console.log(mostExpPilot) // {id: 20,name: "Temmin",years: 30}
15.filter() - returns new array with all the elements that satisfy the condition.
A common use case of .filter() is with an array of objects through their properties.
ex :
let heroes = [
{name: "Batman", franchise: "DC"},
{name: "Ironman", franchise: "Marvel"},
{name: "Thor", franchise: "Marvel"},
{name: "Superman", franchise: "DC"}
];
let marvelHeroes = heroes.filter(hero => hero.franchise==="Marvel");
console.log(marvelHeroes) // [{name: "Ironman", franchise: "Marvel"},{name: "Thor", franchise: "Marvel"}]
16.some() - return true if at least one element in the array satisfy.
Checks if any one of the element in the array satisfies the provided callback function.
ex : let numbers=[-10,0,10];
let result=numbers.some(x=>x<0);
console.log(result) // true
ex : let numbers=[1,2,3,4,5];
let result=numbers.some(x=>x<0);
console.log(result) // true
17. sort() - sort the elements of an array.
The array got sorted in lexicographical order (i.e. alphabetically),
so each integer actually got coerced into a string type.
In order to sort a list in numerical order, the sort() method needs to be passed a
comparison function.
ex : Aescending numerical order
// Sort numerically because default is lexicographical sort:
[3, 8, -10, 23, 19, -4, -14, 27].sort((a,b)=>a-b)
// Output: Array(8) [ -14, -10, -4, 3, 8, 19, 23, 27 ]
ex : Descending numerical sort
// Sort numerically descending, largest to smallest:
[3, 8, -10, 23, 19, -4, -14, 27].sort((a,b)=>b-a)
// Output: Array(8) [ 27, 23, 19, 8, 3, -4, -10, -14 ]
Protecting the original array with .sort() :
The original array intact and prevent it from being changed.
one way of using slice().
ex :
const transactions = [16.37, 2.33, 4.55, 13.44, 1.25]
const sorted = transactions.slice().sort((a,b)=>a-b) // Make a copy with .slice()
console.log(sorted) // Array(5) [ 1.25, 2.33, 4.55, 13.44, 16.37 ]
The .sort() method sorts the array in-place,so if necessary we
can make a copy while sorting by using syntax [...array.sort().
using spread operator(...) or Object.assign()
const transactions = [16.37, 2.33, 4.55, 13.44, 1.25]
const sorted = [...transactions].sort((a,b)=>a-b) // Make a copy with the spread syntax
console.log(sorted) // Array(5) [ 1.25, 2.33, 4.55, 13.44, 16.37 ]
const alsoSorted = Object.assign([], transactions) // Make a copy with Object.assign()
alsoSorted.sort((a,b)=>a-b)
console.log(alsoSorted) // Array(5) [ 1.25, 2.33, 4.55, 13.44, 16.37 ]
18. reduceRight() - this method reduces the array to a single value (right to left).
ex : let arr = ["A", "B", "C", "D", "E"];
let result =arr.reduceRight((previous, current) => previous + current);
console.log(result) // EDCBA
The reduceRight() method works in the same way as the reduce() method, but in the opposite direction.
Note : The reduce() method starts at the first element and travels towards the last,whereas the reduceRight() method
starts at the last element and travels toward the first .