Array methods in JavaScript: when to use which ??

Hey guys ?

There are a lot of array methods in JavaScript and often we get confused ? about which to use when.
In this article I will summarise these methods and do my best to clear about which method should we use according to our needs. …


This content originally appeared on DEV Community and was authored by Mohd Shahid

Hey guys ?

There are a lot of array methods in JavaScript and often we get confused ? about which to use when.

In this article I will summarise these methods and do my best to clear about which method should we use according to our needs.

Let's get started ?

As I said we will study the array methods according to our needs, so just think what do you want...

I want...

1. to mutate the original array

a) add to original array

i) .push:

this method adds an element to the end of the original array and returns the new length of the array.

let numbers = [1,2,3];
number.push(4);
console.log(numbers) // [1,2,3,4]

ii) .unshift:

this method is like .push method, except it adds the element at the start of the original array.

let numbers = [2,3,4];
numbers.unshift(1);
console.log(numbers) // [1,2,3,4]

b) remove from the original array

i) .pop:

this method remove the last element of the array and returns the removed element.

let names = ['Sid', 'Marty', 'John'];
const removedName = names.pop();
console.log(names) // ['Sid', 'Marty']
console.log(removedName) // 'John'

ii) .shift:

.shift is just like .pop except it removes the element from the start.

iii) .splice:

this method is bit tricky, it can remove and/or add the element(s) to the original array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];

// At position 2, remove 1 element and add 2 elements:
fruits.splice(2, 1, "Lemon", "Kiwi");
console.log(fruits) // ["Banana", "Orange", "Lemon", "Kiwi"]

Other mutating array methods which I do not use so frequently are :

i) .reverse

ii) .sort

iii) .fill

2. a new array

If you want a new array, please look at the following array methods:

i) .map:

As a react developer, .map is the most used array method for me. It loops over the array and perform a certain action on each element then returns the new array of the same length.

const numbers = [1,2,3,4];
const numberSqr = numbers.map((num) => num*num);
console.log(numberSqr) // [1,4,9,16]
  • .map receives a callback function, which accepts the following arguments:

    i) The current element being processed in the array.

    ii) index of the current element being processed in the array.

    iii) array on which .map was called.

  • value returned from the callback function will be mapped the corresponding element in the array.

ii) .filter:

This methods creates a new array with all the elements that passed the condition given in the callback function.

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

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

console.log(result);
// ["exuberant", "destruction", "present"]

iii) .slice:

This method returns a copy of the portion of the array.

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

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

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

iv) .concat:

This method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

letters.concat(numbers);
// result is ['a', 'b', 'c', 1, 2, 3]

3. an array index

i) .indexOf:

This method returns the first index at which a given element can be found in the array, or -1 if it is not present.

const fruits = ['Banana', 'Apple', 'Kiwi'];
console.log(fruits.indexOf('Apple')) // 1
console.log(fruits.indexOf('Orange')) // -1

ii) .findIndex:

This method returns the index of the first element that passed a given condition. Otherwise -1 indicating that no element passed the condition.

const numbers = [5,9,2,11,5];
const index = numbers.findIndex((element) => element > 8) // 2
const ind = numbers.findIndex((element) => element > 12) // -1

4. an array element

.find:

This method returns the first element which satisfies a provided condition. undefined otherwise.

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

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

console.log(found);
// 12

5. to know if the array includes

i) .includes:

This methods returns true (if the array contains the element) or false.

const friends = ['Jon', 'Joe', 'Jack', 'Jill'];
console.log(friends.includes('Jon')) // true
console.log(friends.includes('Sid')) // false

ii) .some:

Name of this method sometimes confuse me ?. This method returns true if at least one element passes the given condition.

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

iii) .every:

This method returns true if all the elements in the array pass the given condition, false otherwise.

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

6. a new string

.join:

This methods joins all the element of the array by a given string separator and return the string.

let words = ['JS', 'is', 'amazing'];
// joining the words by space
console.log(words.join(' ')) // 'JS is amazing'

// joining by dash ('-')
console.log(words.join('-')) // 'JS-is-amazing'

7. to just loop over an array

forEach:

This method executes a provided function once for each array element.

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// 'a'
// 'b'
// 'c'

8. to transform the array to a single value

.reduce:

This methods reduces the array to a single value.

This value can be of any type: number, string, boolean, array or object.

The reducer function takes four arguments:

a) Accumulator

b) Current Value

c) Current Index

d) Source Array

Reducer function's 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.

// sum of the elements of the array using .reduce
let numbers = [1,4,5];
const sum = numbers.reduce((acc, el, i, arr) => acc+el);
console.log(sum) // 10

Phew, this was a lot to take in ?.

I hope you guys found this article helpful, if you did please leave a like.

If you need explanation of any particular method, please let me know in the comment section or message me on twitter.

Thanks for reading. ?

Happy coding.


This content originally appeared on DEV Community and was authored by Mohd Shahid


Print Share Comment Cite Upload Translate Updates
APA

Mohd Shahid | Sciencx (2021-08-19T15:55:12+00:00) Array methods in JavaScript: when to use which ??. Retrieved from https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/

MLA
" » Array methods in JavaScript: when to use which ??." Mohd Shahid | Sciencx - Thursday August 19, 2021, https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/
HARVARD
Mohd Shahid | Sciencx Thursday August 19, 2021 » Array methods in JavaScript: when to use which ??., viewed ,<https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/>
VANCOUVER
Mohd Shahid | Sciencx - » Array methods in JavaScript: when to use which ??. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/
CHICAGO
" » Array methods in JavaScript: when to use which ??." Mohd Shahid | Sciencx - Accessed . https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/
IEEE
" » Array methods in JavaScript: when to use which ??." Mohd Shahid | Sciencx [Online]. Available: https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/. [Accessed: ]
rf:citation
» Array methods in JavaScript: when to use which ?? | Mohd Shahid | Sciencx | https://www.scien.cx/2021/08/19/array-methods-in-javascript-when-to-use-which-%f0%9f%a4%94/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.