Important JavaScript array methods, array compare function, and extending array prototype method

Author image
Author

Fashanu T.

02, Feb 2021

4 Minutes Read...


When it comes to working with data in JavaScript, you will come across array and work with several array methods to filter, sort, manage, shuffle and do a whole lot of dope stuff with the data you got.

Without further ado, lets get right to it:

1. Array.concat() method

When you want to join two or more arrays together to become one, you will need the Array.prototype.concat() method for that.

See the sample below:

javascript
var array1 = [1,2,3,4,5]
var array2 = ['six','seven','eight'];
var together = array1.concat(array2);

console.log( together );
// [1,2,3,4,5,"six","seven","eight"];

var arrayOne = [1,2,3];
var arrayTwo = ['three','four','five'];
var arrayThree = [6,7,8];
var arrayFour = [9,0];

console.log(  arrayOne.concat(arrayTwo, arrayThree, arrayFour)  );
// [1,2,3,"three","four","five",6,7,8,9,0];

2. Array.every() method

Array.prototype.every() method is used to test if all elements in an array passed your given expectation.  I.e if you have a bunch of array with numbers and you want to know if they are above a certain threshold i.e 5 or >5 for instance, or check if every element of a JavaScript array is a number, or maybe a string.

If one of the test returns false, it breaks the loop. If all passed, it returns true.

javascript
var array = [1,2,3,4,"5",6,7];
var numbercheck = array.every( function (elem) {
  return typeof elem === 'number';
});

console.log( numbercheck );
//false

var numbers = [6, 9, 7, 4, 3, 8, 0];
var result = numbers.every( function (number) {
  return number > 4;
});

console.log( result );
//false


var arr = ['eddonienoid', 'e9udbeubd', 'eubeif', 'edubuduibeeuibdede', 'eud', 'edibiedbeu'];

var res = arr.every( function(str) {
   return str.length > 2;
});

console.log ( res );
// true

var res = arr.every( function(str) {
   return str.length > 3;
});

console.log ( res );
// false

3. Array.filter() method

The Array.prototype.filter() method is indeed a useful array method in JavaScript. It creates a whole new array of elements that passed a test from a given array.

Lets say we have a bunch of emails/names in an array from a database and we integrated a search feature. We can use the filter method based on a user string input, to filter the closest result out of that array.

Another use case was trying to get all elements that has what i needed from a given array.

Lets take a look at a couple of examples below:

javascript
var arry = [1,3,5,5,6,4,5,5,6,5,4,4,];
var result = arry.filter( function(elem) {
  return elem === 5;
});

console.log( result );
// [5,5,5,5,5]


var names = ['Leeroy Johnson','Johnson Singer','Batman Rob','Superman Bob','Johnny Bravo','David Batman'];
var result =  names.filter( function ( name ) {
  return name.toLowerCase().indexOf('johnson') > -1;
});

console.log( result );
// ["Leeroy Johnson", "Johnson Singer", "Johnny Bravo"]

4. Array.find() method

The Array.prototype.find() method returns the first element from an array that matches a test.

Lets say we have an array of object and we need to confirm one of these object key has a value we need. We can use the find() method in this case.

array.find() method returns the first element of an array that passed a test, and returns undefined if it doesn't find an element from the array that matches our test.

For example:

javascript
var numbers = [1,2,4,5,3];
console.log ( numbers.find( num => num > 2  ) );
// 4

var people = [
  { "name":  "Fashanu Tosin", "age": 23, "Occupation":"Web Developer", "interest": "JavaScript" },
  { "name":  "Bob Castor", "age": 27, "Occupation":"Analyst", "interest": "SQL" },
  { "name":  "Major Laser", "age": 34, "Occupation":"Accounting", "interest": "spreadsheet" }
];

var result = people.find( function (person) { 
  return person.age === 34;
});

console.log( result );
// { "name":  "Major Laser", "age": 34, "Occupation":"Accounting", "interest": "spreadsheet" }

5. Array.forEach() method

Array.prototype.foreach() method is one of the most popular array methods.

The forEach() method is handy if you want to cycle through each element of an array.

Example:

javascript
var elements = [1,2,3,4,5];
var num = 0;
elements.forEach( function (elem) {
  num += elem;
});

console.log( num );
// 15

num  = 0;
elements.forEach( function (elem, index, array) {
  num += elem+ array[index];
});

console.log( num );
// 30

6. Array.includes() method

The Array.prototype.includes() methods lets you search a given array for a value/element, and return true if it finds the element. It however returns false when the result is not found.

Example:

javascript
var arr = [1,2,3,4,5,6,"seven"];
console.log( arr.includes(2) );
// true

cosole.log( arr.includes('seven') );
// true

//arr.includes(elem, fromIndex);

console.log( arr.includes(4, 5) );
//false

console.log( arr.includes(4, -4));
// true

7. Array.join() method

The Array.prototype.join() returns a string by concatenating each element of an array together.

You can also add a separator for these elements.

javascript
var aboutMe = ['My name is Fashanu Tosin', ' i love to code', ' my favourite language is JavaScript'];

console.log( aboutMe.join() );
//My name is Fashanu Tosin, i love to code, my favourite language is JavaScript

console.log( aboutMe.join('-_-') );
//My name is Fashanu Tosin-_- i love to code-_- my favourite language is JavaScript

8. Array.map() method

Array.prototype.map() is one of — if not the most popular array method you must have come across during your development career 😃.

Basically, array.map() method creates a new array when you pass in a function that circles through each element of that array.

var elements = [1,2,3,4,5];

var result = elements.map( function(elem) {
  return elem*2;
});
console.log( result );
//[3, 6, 9, 12, 15]

result = elements.map( function(elem) {
  return elem>3;
});
console.log(result);
//[false, false, false, true, true]

elements = ['Rice','Beans','Carrot','Pepper'];
var html = '
    '; result = elements.map( function(elem) { html += '
  • '+elem+'
  • '; }); html += '
' console.log( html);

9. Array.pop() method

Array.prototype.pop() method is useful when you need to remove the last element in an array.

javascript
var nums = [1,2,3];
nums.pop();

console.log(nums);
// [1, 2]

10. Array.push() method

Array.prototype.push() method is also a popular array method like the Array.prototype.map() method.

The array.push() methods allows you to push new elements, or add new entries to an already existing array.

javascript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi","Carrot");
console.log( fruits ); // ["Banana", "Orange", "Apple", "Mango", "Kiwi", ""Carrot"];

11. Array.slice() method

Array.prototype.slice() method extract a portion from an array into a new array. It takes two values, a start and end.

javascript
var arr = [1,2,3,4,5];
var newArr = arr.slice(1,4);
console.log( newArr );
// [2, 3, 4]

Using negative value in Array.slice() method counts from the back.

javascript
var arr = [1,2,3,4,5,6];
var result = arr.slice(-2, -4);
console.log( result );
// [4,5]

result = arr.slice(1, -3);
console.log( result );
// [2,3,4]

result = arr.slice(-4, 4);
console.log ( result );
// [3,4]

12. Array.some() method

Array.prototype.some() finds out if at least one element in an array passed a test.

It returns a Boolean of true if at least one element passed the test from a function, and return false if non passed the test.

You can think of Array.prototype.some() method as the less lenient brother of Array.prototype.every() method that ensures all the element passes the test for it to return true.

Furthermore, it also means that this method breaks out of the cycle once it finds out that an element passes the test.

javascript
var nums = [1,2,3,4,5];
var result = nums.some( function (num) {
  return num > 4;
});

console.log( result );
// true

result = nums.some( function (num) {
  return num % 2 == 0;
});
console.log( result );
// true
// % is modulus. Which means element 4 divided by 2 = 2 remainder 0 which == 0

13. Array.sort() method

For Array.prototype.sort() method, each element is sorted in numerical, alphabetical, or some other order, based on the function passed into it.

The default sort method is ascending, based on converting each element to string, then comparing there sequence of UTF-16 unit values.

javascript
var arr = ['one','two','three','four'];
arr.sort();
console.log( arr );
// ["four", "one", "three", "two"]

arr = [1, 2, 3, 100000, 4, 5];
arr.sort();
console.log( arr );
// [1, 100000, 2, 3, 4, 5]

arr  = [1, 2, 3, 100000, 4, 5];
arr.sort( function (a,b) { return a-b; } );
console.log( arr );
// [1, 2, 3, 4, 5, 100000]

Using a comparison function inside the Array.prototype.sort() method when dealing with numbers explained:

Comparison function is supplied to arr.some() method with two parameter a, b.

a represent the first element of the loop, b represent the next element.

If a is less than b then a comes first before b, if a is greater than b, then b comes first before a.

If a == b, leave a and b unchanged in there position.

See the example below:

javascript
var arr = [1,2,3,1000,4,5];
arr.sort( function (a,b) {
  if(a>b) return 1;
  if(a<b) return -1;
  return 0;
});

console.log( arr );
// [1, 2, 3, 4, 5, 1000]

Positive return from a>b means a is greater than b and should come after b. Any negative return means a<b and should come before b. The above is the same as the one below:

javascript
var arr = [1,2,3,1000,4,5];
arr.sort( function (a,b) {
  return a-b;
});
console.log( arr );
// [1, 2, 3, 4, 5, 1000]

arr =  [1,2,3,1000,4,5];
arr.sort( function (a,b) {
  return b-a;
})
console.log( arr );
// [1000,5,4,3,2,1]

That is because (a-b) will return either positive or negative number just like the sample above. However, b-a will be the opposite. This is because, you supplied two argument a,b. So therefore, the function you passed in will always use the argument as its reference, which means if b-a is positive: since a is the first argument supplied, b will come first before a.

14. Array.splice() method

The Array.prototype.splice() method is used to add or replace existing elements in an array.

It follows this pattern:

Array.splice(startingArrayIndex, howManyItem(s)ToRemove, item1, item2, item3, item4, .......);

var arr = ['one','two','three','four'];
arr.splice(1, 1, 'five');
console.log( arr );
// ["one", "five", "three", "four"]

arr = ['one','two','three','four'];
arr.splice(1, 0, 'doNOtRemove');
console.log( arr );
// ["one", "doNOtRemove", "two", "three", "four"]

arr = ['one','two','three','four'];
arr.splice(1, 1);
console.log( arr );
// ["one", "three", "four"]

arr = ['one','two','three','four'];
arr.splice(1, 3, 'three','five','seven','nine');
console.log( arr );
// ["one", "three", "five", "seven", "nine"]

arr = ['one','two','three','four','five'];
arr.splice(3);
console.log( arr );
// ["one", "two", "three"]

Extending array (prototype ) methods

If you find yourself in need of extending the basic/generic array methods provided in JavaScript, you can extend array prototype with a polyfill, after that, all generic array will subscribe to that method.

javascript
Array.prototype.toUpperCase = function () {
  for (i = 0; i < this.length; i++) {
  	this[i] = this[i].toUpperCase();
  }
  return this;
}

var arr = ['one','two'];
arr.toUpperCase();
console.log( arr );
// ["ONE", "TWO"]

Generally speaking, you should avoid extending base objects, i.e Array because it may clash with other extensions of that object.

In conclusion, array methods basically simplifies various actions we need to perform on an array.

That's it for today, cheers if you came this far —🍹.

More read:

  1. How to write, test, host and publish JavaScript package to GitHub, NPM & jsDelivr.
  2. All about JavaScript spread operator and accepting any number of argument in a function.
  3. How to create moment.js or use time ago localized date format in JavaScript from scratch.
  4. Most important JavaScript string methods you should know.
  5. Javascript closure in 3 minutes: examples and interview questions.
  6. JavaScript redirect, open new tab redirect without Popup block.
  7. How to send JSON string using AJAX, fetchAPI to php and dealing with 403 error while using AJAX.
  8. Using JavaScript fileReader in converting files to different formats and uses of fileReader.
  9. How to get a free SSL certificate and configure it on your website.
  10. Top 4 free web hosting with domain to consider today.
  11. How to add google maps to website: route, search, street view image, markers, geolocation.