Javascript Array Methods

Table of contents

No heading

No headings in the article.

In programming, an array is a collection of elements or items. Arrays store data as elements and retrieve them back when you need them. The array data structure is widely used in all programming languages that support it.

Some of the Array Methods in JavaScript are as follows:

.map()

The map() method creates a new array by iterating through every elements of an array

const array = [5,7,8,90,34,5,1,3,56]
const result = array.map(x => x*2)
console.log(result)
// [10, 14, 16, 180, 68, 10, 2, 6, 112]

filter()

The filter() method creates a new array with only elements that passes the condition inside the provided function.

const array = [5,7,8,90,34,5,1,3,56]
const result = array.filter(x => x <50)
console.log(result)
[5, 7, 8, 34, 5, 1, 3]

reduce()

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

const array = [5,7,8,90,34,5,1,3,56]
const result = array.reduce((total,current)=>total + current)
console.log(result)
// 209

sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

const months = ['March', 'Jan', 'Feb', 'Dec'];
console.log(months.sort());
//  ["Dec", "Feb", "Jan", "March"]

const nums= [1, 30, 4, 21, 100000];
console.log(nums.sort());
 //  [1, 100000, 21, 30, 4]

some()

This method checks if at least one element in the array that passes the condition, returning true or false as appropriate.

const array = [5,7,8,90,34,5,1,3,56]
const result = array.some(x => x>50)
console.log(result)
// true

const result = array.some(x => x<1)
console.log(result)
// false

every()

This method checks every element in the array that passes the condition, returning true or false as appropriate.

const array = [5,7,8,90,34,5,1,3,56]
const result = array.every(x => x>50)
console.log(result)
// false

const result = array.every(x => x<100)
console.log(result)
// true

push()

The push() method adds one or more elements to the end of an array and returns the new length of the array.

const animals = ['pigs', 'goats', 'sheep'];
console.log(animals.push('cows'));
//  4

console.log(animals);
//  ["pigs", "goats", "sheep", "cows"]

pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

const plants = ['broccoli', 'cauliflower'];

console.log(plants.pop());
// "cauliflower"

console.log(plants);
// ["broccoli"]

These are some of the array elements which we use in day-to-day projects. Next Set of array methods will be coming soon..