27 JavaScript Array methods

27 JavaScript Array methods

An Array is a data structure that contains a group of elements. Array methods are built-in JavaScript functions that we can use on our arrays which helps us to perform a change or calculations without having to write the functions from scratch.

1 concat()

The concat() function merges two or more arrays. It doesn't change the existing arrays but returns a new one array.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const array3 = array1.concat(array2);

console.log(array3)
// expected output: Array ["a", "b", "c", "d", "e", "f"]

2. every()

The every() methods checks if every element in an array pass a test.

const isLessThanForty = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isLessThanForty));
// expected output: true

3. fill()

The fill() method fills an array with a specific value. It accept three parameters

  • the value
    -the start
    -the end
const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

4. filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

5. find()

The find() method returns the first element in an array that passes the test

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

6. findIndex()

The findIndex() method returns the index or the position of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

7. forEach()

The forEach() method executes a function for each element in an array

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

8. from()

The from() method creates an array from any object with a length property

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]

9. includes()

The includes() method checks if an array contains a specified element

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

10. indexOf()

The indexof() method returns the first index at which a given element can be found. It searches an array for an element and returns it position. It returns -1 if the element is not found

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

11. isArray()

This method checks whether an object is an array

Array.isArray([1, 2, 3]);  // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar');   // false
Array.isArray(undefined);  // false

12. join()

The join() method creates and returns a string by concatenating the elements in an array

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

console.log(elements.join(''));
// expected output: "FireAirWater"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

13. keys()

They keys() method returns an array iteration object that contains the keys of each element in an array

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// expected output: 0
// expected output: 1
// expected output: 2

14. lastIndexOf()

The latIndexOf() method searches an array for an element starting from the end and returns the position. The search is backwards(starting from the back) and iit returns -1 if the element is not present

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// expected output: 3

console.log(animals.lastIndexOf('Tiger'));
// expected output: 1

15. map()

The map() method creates a new array with the result of calling a function for each element in an array

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

16. pop()

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

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// expected output: "tomato"

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]

17. push()

This method adds new element(s) to the end of an array and returns the new length of the array

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

18. reduce()

The reduce() method reduces the values in an array into a single value. It executes a function on each element resulting in a single value. It runs from left to right.

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

19. reduceRight()

The reduce right also returns a single value but it runs from right to left

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]

20. reverse()

This method reverses the order of elements in an array. The first element becomes the last and the last element becomes the first

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

21. shift()

The shift() method removes the first element in an array and returns that element. It affects the length of the array

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

22. slice()

The slice() method selects part of an array and returns it as a new array. The original array is not affected. It takes two parameters(which are optional), the start and the end.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

23. some()

This method checks if any of the elements in an 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

24. sort()

The sort() method sorts or rearranges the elements in an array. The default is to sort elements in ascending order but this can be solved by providing a compare function.

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

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a}); 
// Sort the numbers in the array in descending order
// The first item in the array (points[0]) is now the highest value

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});    
// Sort the numbers in the array in ascending order
// The first item in the array (points[0]) is now the lowest value

25. splice()

The splice() method changes the content of an array by adding or removing or replacing them. It accepts three parameters, where to add/remove/replace, the number of elements to delete and the element to be inserted. If the second parameter(the number of elements to remove) is 0, then no element will be removed.

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"]

26. toString()

This method converts an array to string and returns the result

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

27. unshift()

The unshift() method adds new elements to the start of an array. It affects the 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]

If you find this helpful, comment and like. And do not forget to share. Thanks