In this article, we will see some array methods in javascript and their examples.
Creating an Array
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
];
filter()
filter() method is used to create a new array with all the elements satisfying the given function.
// filter all the inventors whose year >1600
const result=inventors.filter(function(inventor){
if(inventors.year >1600) return true;
})
console.log(result)
//[{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },]
)
map()
map() method is used to create a new array with the results of calling a function on every element of the array
// map inventors firstname and lastname and display them
const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`);
console.log(fullNames);
// ["Albert Einstein", "Isaac Newton", "Galileo Galilei", "Marie Curie", "Johannes Kepler", "Nicolaus Copernicus", "Max Planck", "Katherine Blodgett", "Ada Lovelace", "Sarah E. Goode", "Lise Meitner", "Hanna Hammarström"]
reduce()
reduce() function reduces array to a single value.
const array=[10,20,30,40]
var sum=array.reduce(function(total,currentvalue){
return total+currentvalue;
})
console.log(sum)
//100
forEach()
forEach() function calls given function once for each element of array
const array=[1,2,3,4]
array.forEach(element=>console.log(element))
// 1
2
3
4
sort()
The sort() function sorts the elements of array inplace(sorting without any auxiliary data structure). The default sorting is ascending.
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
];
const oldest = inventors.sort(function(a, b) {
const lastInventor = a.passed - a.year;
const nextInventor = b.passed - b.year;
return lastInventor > nextInventor ? -1 : 1;
});
console.table(oldest);
// 0: {first: "Isaac", last: "Newton", year: 1643, passed: 1727}
1: {first: "Galileo", last: "Galilei", year: 1564, passed: 1642}
2: {first: "Albert", last: "Einstein", year: 1879, passed: 1955}
3: {first: "Nicolaus", last: "Copernicus", year: 1473, passed: 1543}
4: {first: "Marie", last: "Curie", year: 1867, passed: 1934}
5: {first: "Johannes", last: "Kepler", year: 1571, passed: 1630}
Thank you and that's all for this article.