DONATE  
MENU
MYSQL
CSS
JAVASCRIPT
PHP
JSON
HTML
AJAX

JavaScript Tutorials

INTRODUCTION

» Introduction to JavaScript

» Practice IT Editor

» JavaScript Example

» JavaScript Placement

» JavaScript Syntax

» JavaScript Statements

» JavaScript Input

» JavaScript Output

» JavaScript Comments

» JavaScript Variables

» Variables' Scope

» JavaScript Operators

» JS Expressions & Concatenation

» JavaScript Data Type

» JavaScript Numbers

» Number Object

» JavaScript Strings

» String Object

» JavaScript Booleans

» Boolean Object

» JavaScript Functions

» JavaScript Arrays

» Array Object - Properties

» Array Object - Methods

» JavaScript Objects

» JavaScript Undefined

» JavaScript Nulls

CONDITIONAL TESTING

» If Statement

» If Else Statement

» JavaScript Ternary Operator

» Switch Statement

LOOPS

» For Loops

» While Loops

» Break & Continue

» For...In Loops

» do...while Loop

FUNCTIONS

» JavaScript Functions

» Creating Functions

» Functions' Parameters

» Functions' Arguments

» Function Invocation

» The Return Keyword

» The Arguments Object

» Callback Functions

» Arrow Functions

ARRAYS

» JavaScript Arrays

» Creating Arrays

» Accessing Arrays

» Looping Arrays

» Multi - dimensional Arrays

OBJECTS

» JavaScript Objects

» Creating Objects

» Prototype Definition

» Accessing Objects

» The this Keyword

AJAX

» Introduction to AJAX

JSON

» Introduction to JSON

JAVASCRIPT DATES

» The Date Object

» Date Methods

» Timing (SetInterval & SetTimeout)

MATH OBJECT

» Math Object

» Math Methods

HTML / JS DOM

» DOM Introduction

» Accessing HTML Elements in DOM

» Get And Change Elements' Contents & Values

» Change Styling - DOM CSS

» DOM Attributes

» JavaScript Event Listeners

» DOM Event Listeners

» JS Events

MISCELLANEOUS

» JS Strict Mode

» JavaScript Hoisting

» JavaScript let keyword

» Reserved Keywords

» JS Best Practices

» JavaScript vs ECMAScript

JAVASCRIPT EXAMPLES

» JavaScript Calculator

.. » JavaScript » Introduction » Array Object - Methods
Share Tweet WhatsApp

Array Object - Methods

Here is a continuation of the properties and methods of the array object.
KeyNote: Beginners are advised to get familiarized with the push(), pop(), sort(), shift(), unshift(), reverse(), concat() and toString() methods only. You can proceed with the tutorial and check back later if the rest of the methods appear a bit difficult to understand.
Methods 1. concat() The concat() method of the arrays' object helps join the values of an array with that of one or more other arrays to create a new array.
<script>
var arr = [1, 2, 3];
var newArr = arr.concat([4,5,6,7]);
alert(newArr);
</script>

Copy PRACTICE IT

<script>
var animals = ["Humans","Apes","Monkeys"];
var dAnimals = ["Orangutans", "Dogs", "Cats", "Squirrels"];
var allAnimals = animals.concat(["Elephants","Snakes","Crocodiles"]).concat(dAnimals);
alert(allAnimals);
</script>

Copy PRACTICE IT

2. every() Similar to the some() method but here, it checks if all the values of an array satisfy a specified condition. It returns true if all values satisfied the condition and false if one or more did not.
<script>
var genders = ["m", "m", "f", "m", "m"];
if (genders.every(gender => gender == "m")){
alert("There are no females in the class.");
}
else
{
alert("There are females in the class.");
}
</script>

Copy PRACTICE IT

Notice the use of an arrow function (gender => gender == "m") assigned as an argument to the every() method. When we assign a function definition as an argument to a function or method, the function is known as a callback function.
3. filter() The filter() method enables you to create an array from an existing array based on a specified condition. For example, if there exists an array of some people's age, you can use the filter method to create a new array of people whose age are above or below a certain level.
<script>
var recruits_age = [16, 21, 25, 18, 15, 20, 34]; //Existing array
var eligible_recruits = recruits_age.filter(r_age => r_age >= 18 && r_age <= 25); //Create new array using the values of the existing array that are greater than or equal to 18 and less than or equal to 25
alert(eligible_recruits); //21, 25, 18, 20
</script>

Copy PRACTICE IT

Instead of specifying a condition, you may decide to replace the condition with the boolean, true to copy all values to the new array.
var eligible_recruits = recruits_age.filter(r_age => true);
4. find() This method enables you to find any value of an array that meets a specified condition. It will return the value if it meets the condition or undefined if none of the values meets the condition.
<script>
var arr = [1, 3, 4, 5, 7];
alert(arr.find(num => num > 3 && num < 5)); //4 - this is because it is looking for an element which is greater than 3 and less than 5 such as 4 and 4 is in the array.
</script>

Copy PRACTICE IT

This method is mostly important when you have an array whose elements or values are objects. And then, you want to find or retrieve any of the objects that meet a specified condition.
<script>
var arr = [{name: "Facebook", year: 2006}, 
{name: "A website", year:2010}, 
{name: "StackBeginner", year:2020}];
alert(JSON.stringify(arr.find(website => website.year == 2020))); //{name: "StackBeginner", year:2020}
</script>

Copy PRACTICE IT

In the above is an array whose values are objects. Each object contained a website and its founding year and the task was to find any of the website whose founding year was 2020. The find() method helped us to achieve that. 5. findIndex() Almost same thing as the find() method but here, if a value is found, it will return the index/key of the value instead of the value itself.
<script>
var arr = [1, 3, 4, 5, 7];
alert(arr.findIndex(num => num > 3 && num < 5)); //2 - this is because it is looking for an element which is greater than 3 and less than 5 such as 4 and 4 is in the array at index position 2
</script>

Copy PRACTICE IT

6. forEach() The forEach() method enables you to use all the individual values of an array as arguments to invoke a function. In order words, it allows you to invoke a function on the values of an array.
<script>
function myFunc(value){
document.write(value+" is part of the executives.<br/>");
} //a function

var people = ["Jessica", "Benson", "Ada"]; //array
people.forEach((person) => myFunc(person));
</script>

Copy PRACTICE IT

In the above, the forEach() continually invoked the function (myFunc()) while passing all the values of the array as arguments to it till all values were assigned. 7. from() The from() is a static method meaning you don't invoke it on an array value but rather, directly on the Array object prototype. The method enables you to create an array using the values of an already existing array or string. What distinguishes this method from methods such as the map(), filter(), slice() method is that it creates an array from a string too.
<script>
//CREATING ARRAY FROM STRING
var str = "HTML"; //string
var arr = Array.from(str); //Creates a array using the string
alert(arr); //H, T, M, L
</script>

Copy PRACTICE IT

<script>
//CREATING ARRAY FROM ARRAY
var arr = ["HTML", "CSS", "JS"]; //array
var newArr = Array.from(arr); //Creates an array using the arr given in its parameter
alert(arr); //HTML, CSS, JS
</script>

Copy PRACTICE IT

8. includes() The includes() method checks if an array includes a value or if any value of an array matches with a specified value or not. It will return true if the array includes the value.
<script>
var web = ["HTML", "CSS", "JS", "PHP", "MySQL"];
if (web.includes("Python")){//false
alert("Python is among the languages used for the website.");
}
else{
alert("Python is not among the languages used for the website");
}
</script>

Copy PRACTICE IT

9. indexOf() Just like its string equivalent, the indexOf() method searches for an element in an array starting from the beginning of the array. It will return the key/index of the first instance of that element if found or -1 if no instance of the element was found.
<script>
var arr = [50, 45, 50, 25, 45, 10];
alert(arr.indexOf(45)); //1 - 1 is the index of the first instance of 45
</script>

Copy PRACTICE IT

10. isArray() Remember when you use the typeof() operator on an array, it returns object thereby making it impossible to use the operator in testing if a value is an array or another form of object. Anyways, the isArray() is a static method of the array object that enables you to test if a value is an array or not. It returns true if the value is an array.
<script>
var arr = [1];
alert(Array.isArray(arr)); //true
</script>

Copy PRACTICE IT

11. join() The join() method enables you to convert an array to a string while you also specify how the values of the array should be joined together in forming the string. When we use the toString() method to convert an array to a string, the string is created by joining the values together with a comma(,) but with the join() method, you can actually specify just anything in replacement of commas(,).
<script>
var arr = [1, 2, 3, 4, 5]; //array
arr = arr.join("%%%"); //The string will be 1%%%2%%%3%%%4%%%5%%%

alert(arr); //string
</script>

Copy PRACTICE IT

You can use practically any sign to join the values together e.g dot(.), asterisk(*), dollar sign($), question mark(?) and yes, just anything. 12. lastIndexOf() Almost like the indexOf() method, the lastIndexOf() method searches for an element in an array starting from the end of the array. It will return the key/index of the last instance of that element if found or -1 if no instance of the element was found.
<script>
var arr = [50, 45, 50, 25, 45, 10];
alert(arr.lastIndexOf(45)); //4 - 4 is the index of the last instance of 45
</script>

Copy PRACTICE IT

NOTE:
  • Both the indexOf() and lastIndexOf() method won't be able to search for NaN as a value.
    <script>
    var arr = [NaN, NaN, NaN];
    alert(arr.indexOf(NaN)); //-1 meaning it was not found though it exists
    </script>

    Copy PRACTICE IT

    Therefore, if you must check if any of an array value is NaN, use the includes() method.
    <script>
    var arr = [NaN, NaN, NaN];
    alert(arr.includes(NaN)); //true
    </script>

    Copy PRACTICE IT

13. map() Just like the filter() method, this method creates a new array from an existing one by manipulating or changing the values of the previous array. For example, you can create a new array from an existing one by adding a value to all the values of the previous one.
<script>
var arr = [1, 2, 3]; //Existing array
var newArr = arr.map(value => value + 10); //creates new array by adding 10 to the individual values of the existing array
alert(newArr); //11, 12, 13
</script>

Copy PRACTICE IT

You can also add strings or characters.
<script>
var amounts = [150, 59, 310];
var amounts_in_dollar = amounts.map(amount => "$" + amount);
alert(amounts_in_dollar); //$150, $59, $310
</script>

Copy PRACTICE IT

Or better still, nothing.
<script>
var arr = [45,15, 10, 80]; //Existing array
var newArr = arr.map(value => value); //Creating array using the values of the existing array
alert(newArr) //45, 15, 10, 80;
</script>

Copy PRACTICE IT

14. pop() The pop() method as oppose the push() method removes a value from an array. The pop() will remove the last value of an array when used on the array.
<script>
var arr = ["Nigeria", "America", "Tanzania", "U.K"];
arr.pop(); //Removes 'U.K' as a value from the array
alert(arr);
</script>

Copy PRACTICE IT

15. push() This method allows you to add a new value at the end of an already existing array. Once added, the new value becomes a value of the array. This even allows you to create an empty array and thereafter add or push in whatever value(s) it should contain.
<script>
var arr = ["Nigeria", "America", "Tanzania"];
arr.push("China"); //Adds 'China' to the end of the array
alert(arr);
</script>

Copy PRACTICE IT

<script>
var arr = []; //empty array
arr.push("Stackbeginner"); //adds 'Stackbeginner'
arr.push("Facebook"); //adds 'Facebook'
arr.push("Google"); //adds 'Google'
alert(arr);
</script>

Copy PRACTICE IT

16. reduce() Instead of looping through an array in order to obtain a single value from an array. For example, add all the numbers in an array of numbers or concatenate the string values of an array, you can use the reduce() method to achieve that. The new value can be of any data type (number, string, array, object) depending on the values of the array.
<script>
var cost = [10, 8, 4]; //array
var totalCost = cost.reduce((total, currentValue) => total + currentValue); //adds all the values of the array together
alert(totalCost); //22
</script>

Copy PRACTICE IT

<script>
var strArr = ["Hello", "Sir", "Frederick Taylor"]; //array
var str = strArr.reduce((str, strValue) => str +" "+ strValue); //concatenates the string values of the array
alert(str); //Hello Sir Frederick Taylor
</script>

Copy PRACTICE IT

17. reverse() Just as the name suggest, the reverse() method enables you to reverse the order in which the elements of an array were defined or created. It doesn't sort the array, it only reverses the position of the values thereby making the first element last and the last element first. For example, reversing 4, 2, 6 will return the array as: 6, 2, 4.
<script>
var array = ["Boy", "Dog", "Apple", "Cat"];
//The array order is currently Boy, Dog, Apple, Cat
array.reverse();
//The array order has now been reversed to the following order - Cat, Apple, Dog, Boy
alert(array);
</script>

Copy PRACTICE IT

18. shift() The shift() method of the JavaScript arrays' object is similar to the pop() method. The major difference is, the shift() method will remove the first element of the array while pop() will remove the last element.
<script>
var arr = ["Nigeria", "America", "Tanzania"];
arr.shift(); //Removes the first element "Nigeria" from the array
alert(arr);
</script>

Copy PRACTICE IT

19. slice() Extracts or takes out one or more elements of an array to form another array. It has two parameters. The first is to indicate the index of the element to start from and the last indicates the element (not inclusive) to stop at. Leave the second argument to return all elements thereafter or better still, leave the two arguments to extract all the elements to create a new array.
<script>
var currencies = ["Dollar","Naira","Kobo","Cedis","Rand","Rupees","Pounds"];
var nigeriaCurrencies = currencies.slice(1,3); //Extracts Naira and Kobo to form the new array
alert(nigeriaCurrencies);
</script>

Copy PRACTICE IT

20. some() The some() method enables you to specify a condition and thereafter check if one or more values of an array satisfies that condition. It returns true if any value satisfies the condition and false if none.
<script>
var scores = [40, 15, 45, 50];
if (scores.some(score => score >= 45)){ //true
alert("One or more candidates scored up to 45 points.");
}
else
{
alert("No candidate score up to 45 points.");
}
</script>

Copy PRACTICE IT

In the above, using the some() method, we checked an array containing the scores of some anonymous candidates to determine if one or more of the candidates scored up to 45. It will return true since a candidate scored 45 and another, 50. 21. sort() The sort() method enables you to sort or rearrange an array in either ascending or descending order. You can sort an array containing string values to be arranged from A - Z (Ascending) or Z - A (Descending) and you can also sort that of numerical values to be arrange from the lowest number to the highest (Ascending) or highest to lowest (Descending).
<script>
var array = ["Boy", "Dog", "Apple", "Cat"];
//The array order is currently Boy, Dog, Apple, Cat
array.sort();
//The array order has now been sort in ascending order - Apple, Boy, Cat, Dog
alert(array);
</script>

Copy PRACTICE IT

22. splice() The splice() method basically allows you to remove multiple elements from an array and even add multiple elements at once. The syntax is,
array.splice(starting_index, number_of_elements_to_remove, elements_to_add);
The method accepts 3 basic kind of arguments. The first specify the index key or number of the element to start removing from e.g 1 to start from the second element while the second argument specify the number of elements to remove e.g 2 to remove two elements. Finally, you can list more optional arguments which will be elements to replace the removed elements.
<script>
var arr = ["Nigeria", "America", "Tanzania"];
arr.splice(0, 2); //Starting from the first element, it removes 2 elements e.g Nigeria, America
alert(arr);
</script>

Copy PRACTICE IT

<script>
var arr = ["Nigeria", "America", "Tanzania"];
arr.splice(0, 2, "Asia", "Algeria"); //Starting from the first element, it removes 2 elements e.g Nigeria, America and then, adds Asia and Algeria to replace them
alert(arr);
</script>

Copy PRACTICE IT

<script>
var arr = ["Nigeria", "America", "Tanzania"];
arr.splice(-2, 2, "Asia", "Algeria"); //Starting from the second to the last element, it removes 2 elements e.g America, Tanzania and then, adds Asia and Algeria to replace them
alert(arr);
</script>

Copy PRACTICE IT

23. split() The split() method is the opposite of the join() method. It creates an array by breaking a string at a specified point and using the individual parts as its element. For example,
<script>
var str = "Hello My People";
var arr = str.split(" "); //Breaks the string wherever there is an open space and create an array with the individual parts from the split forming individual elements
alert(arr);
</script>

Copy PRACTICE IT

You can split a string with any character e.g dots, dollar sign, asterisks and etcetera.
<script>
var str = "Hello.Stack.Beginner";
var arr = str.split("."); //Split wherever there is a dot
alert(arr);
</script>

Copy PRACTICE IT

24. toString() The toString() method enables you to convert an array to a string with its values separated by a comma(,).
<script>
var arr = [1, 2, 3, 4, 5]; //array
arr = arr.toString(); //The array is now a string

alert(typeof(arr)); //string
</script>

Copy PRACTICE IT

Remember, you should store the string version of the array on a variable. Above, it was stored on the array variable(arr) but it can be just any other variable. 25. unshift() The unshift() method of the JavaScript arrays' object is similar to the push() method. The major difference is, the unshift() method adds a new value at the beginning of the array while push() adds a new element at the end.
<script>
var arr = ["Nigeria", "America", "Tanzania"];
arr.unshift("China"); //Adds 'China' to the beginning of the array thereby making it the first element
alert(arr);
</script>

Copy PRACTICE IT

Do not copy array values from one variable to another by assignment This is because when you copy array values from one variable to another by assignment, any modification to any of the array e.g addition or removal of an element affects the other(s). If you must copy the values of an array from one variable to another, use methods such as map(), filter(), from() and others.
<script>
var arr = ["HTML", "CSS", "JS"]; //Existing array
var newArr = arr; //assigns the Existing array to this variable
arr.push("PHP"); //adds a value to the existing array but this will also affect the newArr variable
alert(newArr); //HTML, CSS, JS, PHP
</script>

Copy PRACTICE IT

SUMMARY
  • All JavaScript arrays whether created explicitly or implicitly has an object containing properties and methods.
  • These methods were listed in this page.
Take a short quiz on Array Object - Methods.
Ask a question or tell us if Array Object - Methods is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode