10 JavaScript array methods you should know

Frugence Fidel on June 24, 2018

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 ar... [Read Full]
markdown guide
 

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?

 
 

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.

 
 

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];
?

 

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)

 

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!

 
 

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

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

Your quote from MDN has nothing to do with the question though.
const arr = [7] and const arr = Array.of(7) will give exactly the same resut.

> const arr1 = Array(7);
> const arr2 = [7];
> const arr3 = Array.of(7);

> arr1
[ <7 empty items> ]
> arr2
[ 7 ]
> arr3
[ 7 ]
> 
 

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.

 

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.
 

... 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.

 

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

 

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.

 

I'd say it complements them, not replaces (especially map). By example:

const snakeToCamel = str => str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());

const camelizeKeys = (obj) =>
  Object.keys(obj)
    .map(k => ({ [snakeToCamel(k)]: obj[k] }))
    .reduce((acc, o) => Object.assign(acc, o), {});

note that using forEach, map, and reduce is much slower than simple for loop. But unless you transform thousands of objects it probably doesn't matter.

Thanks for mentioning performance, though I avoid for loops for stuff like this now after too many times having the loop somehow end up using only the last value in the array for all iterations.

 

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

 

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

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.

 

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

 

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

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

 
 

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

 
 

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

 
 
 

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

 
 

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

 

Hello there! Very cool article, thank you. I had a question. Can I translate this article into my native language? And, may I write a non-English language article on Dev.to?

 
code of conduct - report abuse