DEV Community

Frugence Fidel
Frugence Fidel

Posted on • Updated on

JavaScript forEach 10 JavaScript array methods you should know

This post is originally published to my blog.

In this post i will share 10 JavaScript array methods you should know.

If you know nothing about array, you can click here for array introduction.

Here are 10 javascript array methods you should at least know

1. forEach()

This method can help you to loop over array's items.

  const arr = [1, 2, 3, 4, 5, 6];

  arr.forEach(item => {
    console.log(item); // output: 1 2 3 4 5 6
  });
Enter fullscreen mode Exit fullscreen mode

2. includes()

This method check if array includes the item passed in the method.

  const arr = [1, 2, 3, 4, 5, 6];

  arr.includes(2); // output: true
  arr.includes(7); // output: false
Enter fullscreen mode Exit fullscreen mode

3. filter()

This method create new array with only elements passed condition inside the provided function.

  const arr = [1, 2, 3, 4, 5, 6];

  // item(s) greater than 3
  const filtered = arr.filter(num => num > 3);
  console.log(filtered); // output: [4, 5, 6]

  console.log(arr); // output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

4. map()

This method create new array by calling the provided function in every element.

  const arr = [1, 2, 3, 4, 5, 6];

  // add one to every element
  const oneAdded = arr.map(num => num + 1);
  console.log(oneAdded); // output [2, 3, 4, 5, 6, 7]

  console.log(arr); // output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

5. reduce()

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value - MDN

  const arr = [1, 2, 3, 4, 5, 6];

  const sum = arr.reduce((total, value) => total + value, 0);
  console.log(sum); // 21
Enter fullscreen mode Exit fullscreen mode

6. some()

This method check if at least one of array's item passed the condition. If passed, it return 'true' otherwise 'false'.

  const arr = [1, 2, 3, 4, 5, 6];

  // at least one element is greater than 4?
  const largeNum = arr.some(num => num > 4);
  console.log(largeNum); // output: true

  // at least one element is less than or equal to 0?
  const smallNum = arr.some(num => num <= 0);
  console.log(smallNum); // output: false
Enter fullscreen mode Exit fullscreen mode

7. every()

This method check if all array's item passed the condition. If passed, it return 'true' otherwise 'false'.

  const arr = [1, 2, 3, 4, 5, 6];

  // all elements are greater than 4
  const greaterFour = arr.every(num => num > 4);
  console.log(greaterFour); // output: false

  // all elements are less than 10
  const lessTen = arr.every(num => num < 10);
  console.log(lessTen); // output: true
Enter fullscreen mode Exit fullscreen mode

8. sort()

This method used to arrange/sort array's item either ascending or descending order.

  const arr = [1, 2, 3, 4, 5, 6];
  const alpha = ['e', 'a', 'c', 'u', 'y'];

  // sort in descending order
  descOrder = arr.sort((a, b) => a > b ? -1 : 1);
  console.log(descOrder); // output: [6, 5, 4, 3, 2, 1]

  // sort in ascending order
  ascOrder = alpha.sort((a, b) => a > b ? 1 : -1);
  console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y']
Enter fullscreen mode Exit fullscreen mode

9. Array.from()

This change all thing that are array-like or iterable into true array especially when working with DOM, so that you can use other array methods like reduce, map, filter and so on.

  const name = 'frugence';
  const nameArray = Array.from(name);

  console.log(name); // output: frugence
  console.log(nameArray); // output: ['f', 'r', 'u', 'g', 'e', 'n', 'c', 'e']
Enter fullscreen mode Exit fullscreen mode

working with DOM

  // I assume that you have created unorder list of items in our html file.

  const lis = document.querySelectorAll('li');
  const lisArray = Array.from(document.querySelectorAll('li'));

  // is true array?
  console.log(Array.isArray(lis)); // output: false
  console.log(Array.isArray(lisArray));  // output: true
Enter fullscreen mode Exit fullscreen mode

10. Array.of()

This create array from every arguments passed into it.

  const nums = Array.of(1, 2, 3, 4, 5, 6);
  console.log(nums); // output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Oldest comments (34)

Collapse
 
nans profile image
Nans Dumortier

Hey! Thanks for your article 😃
I knew most of them, except the last one. By the way, I was wondering : in which case :
const nums = Array.of(1, 2, 3, 4, 5, 6);
is better than :
const nums = [1, 2, 3, 4, 5, 6];
?

Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez • Edited

I think it's more likely to compare it to the array constructor. According to MDN

The difference between Array.of() and the Array constructor is in the handling of integer arguments: Array.of(7) creates an array with a single element, 7, whereas Array(7) creates an empty array with a length property of 7 (Note: this implies an array of 7 empty slots, not slots with actual undefined values).

I didn't know this method either!

Collapse
 
nans profile image
Nans Dumortier

Thanks, I didn't know about that !

Collapse
 
warix3 profile image
Warix3

He asked about [1, 2, 3, 4, 5, 6] and not Array(7), is it the same?

Thread Thread
 
tunaxor profile image
Angel Daniel Munoz Gonzalez

it is essentially the same, I just pointed out what is a better comparison case with quote from the mdn docs

Collapse
 
wlievens profile image
Wouter Lievens • Edited

It's the same, but one is a function whereas the other is a syntactical form. You could have a situation where you pass it as a parameter or in a variable, i.e.


f = Array.of
...
a = f(1,2,3)

Collapse
 
thiruppathi profile image
Thiru

Thanks for the article Frugence! 👍

I would like to use [...] SpreadOperator a shorthand alternate to Array.from()

const lisArray = [... document.querySelectorAll('li')];

I wonder is there any major difference between these 2 ways?

Collapse
 
frugencefidel profile image
Frugence Fidel

Take a look here friend, Array.from() vs spread syntax

Collapse
 
thiruppathi profile image
Thiru

Thanks for the reference friend. 👍

Thread Thread
 
frugencefidel profile image
Frugence Fidel

You are welcome friend

Collapse
 
dan503 profile image
Daniel Tonon • Edited

Based on that, the answer is essentially "no, they are practically the same" for most use cases.

For some edge cases they do have differences. In those specific edge cases Array.from() is the better one to use.

Collapse
 
michealjroberts profile image
Michael Roberts

Hi Frugence. Is it possible to also outline which ones are supported by ES5 browsers etc.

Collapse
 
pbkarlsson profile image
Philip Karlsson

MDNs documentation covers every array.prototype method, and which browsers that supports which methods:

developer.mozilla.org/en-US/docs/W...

Collapse
 
frugencefidel profile image
Frugence Fidel

Hi buddy, try this caniuse.com

Collapse
 
paulmojicatech profile image
paulmojicatech

This is a great article with succinct and concrete examples. Thanks!

Collapse
 
mattd429 profile image
Matthew Brown

This is great thank you!

Collapse
 
elly1976 profile image
Elly1976

Thanks for the article man.great stuff

Collapse
 
teekatwo profile image
Tori Pugh

Thanks for the article. Opened my eyes to so many ways to manipulate arrays.

Collapse
 
martinhaeusler profile image
Martin Häusler

Does anybody else think that Array#includes(...) is a failure in naming? Every other core library I can think of right now (Java, C#, Kotlin...) calls it #contains(...). Except for JavaScript. I stumble upon that every time I need it, I have to look it up.

Collapse
 
pconnors profile image
Patrick Connors

You can thank MooTools for that: github.com/tc39/Array.prototype.in...

This proposal was formerly for Array.prototype.contains, but that name [is not web-compatible](https://esdiscuss.org/topic/having-a-non-enumerable-array-prototype-contains-may-not-be-web-compatible). Per the November 2014 TC39 meeting, the name of both String.prototype.contains and Array.prototype.contains was changed to includes to dodge that bullet.
Collapse
 
martinhaeusler profile image
Martin Häusler

... and every programmer ever since (who did not start out with JS as their first language) bites that very bullet that they were trying to dodge. Just because of one library? Hahaha, made my day, this is so very web-like.

Collapse
 
gggustafson profile image
gggustafson

You ever heard that a black background color makes reading more difficult?

Collapse
 
daanwilmer profile image
Daan Wilmer

Your explanation for sort is incomplete. First of all, you don't have to provide a comparison function - although the array is then sorted by text value ascending. ['bob', 'alice', 'barbara'] gets sorted as expected, [3, 4, 21 100] does not (it becomes [100, 21, 3, 4]).

More importantly, though: the comparison function is expected to return 0 (zero) when the two elements are equal. Although the used sorting algorithm can probably deal without this, it's still better to return 0 to conform to the spec. It might even speed up the code in certain specific cases.

Collapse
 
zalithka profile image
Andre Greeff • Edited

There's one critical point of .sort() that I feel you should mention in the article: the .sort() method sorts an array in place, it does not return a sorted copy of the array...

Basically, if you do the following:

const myThings = [5,2,4,3,6,1];
const sortedThings = myThings.sort();

..then both variables will contain the same thing:

myThings; // [1,2,3,4,5,6]
sortedThings; // [1,2,3,4,5,6]
myThings === sortedThings; // true

With this in mind, your example could be simplified to the following:

const arr = [1, 2, 3, 4, 5, 6];
const alpha = ['e', 'a', 'c', 'u', 'y'];

// sort in descending order
arr.sort((a, b) => a > b ? -1 : 1);
console.log(arr); // output: [6, 5, 4, 3, 2, 1]

// sort in ascending order
alpha.sort((a, b) => a > b ? 1 : -1);
console.log(alpha); // output: ['a', 'c', 'e', 'u', 'y']
Collapse
 
mednb1 profile image
Med Oubari

Great Post!

Collapse
 
qequ profile image
λlvaro Frias

Very nice useful methods man! but it's not so clear the forEach() example. Anyway, thank you

Collapse
 
vyasriday profile image
Hridayesh Sharma

This is really very helpful. Thanks for this article.

Collapse
 
frugencefidel profile image
Frugence Fidel

You are welcome friend

Collapse
 
_tommylong profile image
Tommy Long

My personal tip is learn .reduce as soon as possible. It intimidated me for a long time and I used .forEach a lot. Once you get reduce you'll suddenly realise how powerful and straight-forward it is and basically never use .forEach again

Collapse
 
jsn1nj4 profile image
Elliot Derhay • Edited

Isn't reduce mainly for working with current values and a total value? How would that take the place of something like .forEach() entirely?

Granted, I do think I have a use case for it, but I don't yet see the need for replacing something like .forEach() or .map() entirely.

Collapse
 
_tommylong profile image
Tommy Long

My main use case for using .forEach before discovering .reduce was because I wanted to transform one object into a new object with a different shape. I'd create an empty object and then .forEach the original object's Object.entities/keys to add properties to the empty object, whereas this is more concise by simply using a .reduce