DEV Community

Cover image for Javascript Array Methods You Should/Must Know....
Shashi
Shashi

Posted on • Updated on

Javascript Array Methods You Should/Must Know....

There are many array methods in Javascript but I will discuss the ones that are most useful and important.

Before, I delve into those methods. Let's get the basics down.

Okay, First of all, What is an array?
->> An array is a list/collection of values/items/elements that are stored in a special variable or else simply we can define it as "A single special variable which stores multiple values/items/elements". These multiple values can be of same datatype or different datatypes.

Note: I used long descriptive variable names according to its functionality just to understand them better. In general, variable names should be concise and meaningful.

// An Array Example With Same Datatype
let same_datatype = ["HTML", "CSS", "Javascript"]; // string
    console.log(same_datatype); // ["HTML", "CSS", "Javascript"]

// An Array Example With Multiple Datatypes
let multi_datatypes = [
    1, // number
    "Coding", // string
    true, // boolean,
    ["HTML", "CSS", "Javascript"], // array
    {author: "Shash", location: "the U.K"} // object
    ]; 
    console.log(multi_datatypes); 
// 0: 1
// 1: "Coding"
// 2: true
// 3: ["HTML", "CSS", "Javascript"]
// 4: {author: "Shash", location: "the U.K"}
Enter fullscreen mode Exit fullscreen mode

Okay, how do you create an array?

// Syntax: let squareBracket_array = [];
let squareBracket_array = [1, "Javascript", true]; 
Enter fullscreen mode Exit fullscreen mode

-> We call this way of creating an array as array literal method.

Great! is this the only way to create an array?
Not actually, there's another way.

// Syntax: let keyword_new_array = new Array();
let keyword_new_array = new Array(1, "Javascript", true); 
Enter fullscreen mode Exit fullscreen mode

By consoling them, We get the same results.

let squareBracket_array = [1, "Javascript", true];
console.log(squareBracket_array); // [1, "Javascript", true]

let keyword_new_array = new Array(1, "Javascript", true);
console.log(keyword_new_array); // [1, "Javascript", true]
Enter fullscreen mode Exit fullscreen mode

Okay, which one to use then?
-> For simplicity, readability and execution speed, use the former one, the array literal method.



Alright, let's jump into sea of some array methods:

I categorised these array methods into three different sections:

1. Add/Remove Array Methods:

  • push() Method: - This method adds element/s at the end of an array and returns the new length.

Syntax:

array.push(element1, element2, ..., elementX); // Parameters are required
Enter fullscreen mode Exit fullscreen mode

Example:

let add_element_at_the_end = ["HTML", "CSS", "Javascript"]; 
    add_element_at_the_end.push("PHP");

    console.log(add_element_at_the_end); // ["HTML", "CSS", "Javascript", "PHP"] 
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. push() method takes argument/s.
  2. push() method returns new array length.

  • pop() Method: - This method removes the last element of an array and returns that element.

Syntax:

array.pop(); // No Parameter/s are required
Enter fullscreen mode Exit fullscreen mode

Example:

let remove_element_at_the_end = ["HTML", "CSS", "Javascript"]; 
    remove_element_at_the_end.pop();

    console.log(remove_element_at_the_end); // ["HTML", "CSS"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. pop() method takes no argument/s.
  2. pop() method returns removed element from the array.
  3. pop() method returns new array length.

  • unshift() Method:- This method adds new element/s at the beginning of an array.

Syntax:

array.unshift(element1, element2, ..., elementX); // Parameters are required
Enter fullscreen mode Exit fullscreen mode

Example:

let add_element_at_the_start = ["CSS", "Javascript"]; 
    add_element_at_the_start.unshift("HTML");

    console.log(add_element_at_the_start); // ["HTML", "CSS", "Javascript"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. unshift() method takes argument/s.
  2. unshift() method returns new array length.

  • shift() Method:- This method removes first element of an array.

Syntax:

array.shift(); // No Parameter/s are required
Enter fullscreen mode Exit fullscreen mode

Example:

let remove_element_at_the_start = ["HTML", "CSS", "Javascript"]; 
    remove_element_at_the_start.shift();

    console.log(remove_element_at_the_start); // ["CSS", "Javascript"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. shift() method takes no argument/s.
  2. shift() method returns removed element from the array.
  3. shift() method returns new array length.

  • splice() Method:- This method adds/removes elements to/from an array. Basically, It’s a method which changes the content of an array by adding the new elements or removing the old one's.

Syntax:

array.splice(index, how many, element1, ....., elementX);
// "index" parameter is required whereas "how many" and "element1, ....., elementX" are optional. 
Enter fullscreen mode Exit fullscreen mode

Let's examine both:

->splice() Add Method:- This method adds new element/s on a specified position in an array and returns the deleted elements (if any).

Example:

let splice_add = ["HTML", "CSS", "Javascript"];
    splice_add.splice(2, 1, "PHP", "SQL");

    console.log(splice_add); //["HTML", "CSS", "PHP", "SQL"] 
/* Explanation:
First parameter (2) defines the index where we want the new elements to be added. In this case, we want to add the new elements on the JavaScript position. 
Second parameter (1) defines how many element/s we want to remove. In this case, we want to remove only one element i.e, JavaScript. 
Rest of the parameters, In this case ("PHP", "SQL") defines the new elements that are going to be added. 
*/
Enter fullscreen mode Exit fullscreen mode

In a nutshell, it looks like this

Original Array - ["HTML", "CSS", "Javascript"]; 
New Array - ["HTML", "CSS", "PHP", "SQL"];
Removed Element - Javascript; 
Enter fullscreen mode Exit fullscreen mode

->splice() Remove Method:- This method removes element/s on a specified position in an array with no new element/s will be added.

Example:

let splice_remove = ["HTML", "CSS", "Javascript"]; 
    splice_remove.splice(0, 1);

    console.log(splice_remove); // ["CSS", "Javascript"]
/* Explanation:
First parameter (0) defines the index of the element that needs to be removed. In this case, we want to remove "HTML" element. 
Second parameter (1) defines, how many element/s we want to remove. In this case, we want to remove only one, "HTML" element.  
Enter fullscreen mode Exit fullscreen mode

In a nutshell, it looks like this

Original Array - ["HTML", "CSS", "Javascript"]; 
New Array - ["CSS", "Javscript"];
Removed Element - HTML; 
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. splice() method changes the original array.
  2. splice() method can be used to add/remove any element in an array where as push, pop, shift and unshift methods performs only designated positions.

  • slice() Method: This method creates a new array by slicing out a piece of an original array.

Syntax:

array.slice(start, end); 
// Both "start" and "end" are optional parameters
Enter fullscreen mode Exit fullscreen mode

Example:

let slice_array = ["HTML", "CSS", "Javascript", "PHP", "SQL"];
let new_slice_array = slice_array.slice(2);

console.log(new_slice_array); // ["Javascript", "PHP", "SQL"]
/* Explanation: 
The above example slices out a part of original array, i.e, slice_array starting from an array element position at 2 ("Javascript") and stores it in the new array called new_slice_array. 
*/
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. The slice() method returns the selected elements in an array, as a new array object.
  2. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
  3. slice() method doesn't remove any elements from the original/source array.
  4. The original array will not be changed.

  • concat() Method: This method creates a new array by combining/merging/concatenating existing arrays.

Syntax:

array1.concat(array2, array3, ..., arrayX);
// Parameters are required
Enter fullscreen mode Exit fullscreen mode

Example:

let frontEnd_lang = ["HTML", "CSS", "Javascript"];
let backEnd_lang = ["PHP", "Python", "Java"];
let fullStack_lang = frontEnd_lang.concat(backEnd_lang);
console.log(fullStack_lang); // ["HTML", "CSS", "Javascript", "PHP", "Python", "Java"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. concat() method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.


2. Searching Array Methods:

  • indexOf() Method: This method returns the position of the first occurrence of a specified value in a string. If the searched value didn't exist, it returns -1.

Syntax:

array.indexOf(item, start);
// parameter "item" is required but "start" parameter is optional
Enter fullscreen mode Exit fullscreen mode

Example:

let reg_str = "Search a string using indexOf method";
let index_str = reg_str.indexOf("indexOf");
    console.log(index_str); // 22
// Start counting the characters of given string from zero including spaces and we will find the first occurrence of indexOf with "i" being at position 22.

let reg_str = "Search a string using indexOf method";
let index_str = reg_str.indexOf("!");
    console.log(index_str); // -1
// "!" didn't existed in the string, so it returned -1 as expected. 
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. The indexOf() method searches the array for the specified item, and returns its position.
  2. The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.
  3. If the item is present more than once, the indexOf method returns the position of the first occurrence.

  • includes() Method: This method determines whether the characters of a specified string is included or not in a given string. It returns true if it's included and false otherwise.

Syntax:

array.includes(element, start);
// parameter "element" is required but "start" parameter is optional
Enter fullscreen mode Exit fullscreen mode

Example:

let reg_str = "Javascript array methods you should know";
let include_str = reg_str.includes("array");
console.log(include_str); // true 

let reg_str = "Javascript array methods you should know";
let include_str = reg_str.includes("arrays");
console.log(include_str); // false 
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. The includes() method is case sensitive.

  • filter() Method: This method creates an array filled with all array elements that pass a condition (provided as a function).

Syntax:

array.filter(function(currentValue, index, arr), thisValue);
// function(currentValue, index, arr) is required but "thisValue" is optional. 
Enter fullscreen mode Exit fullscreen mode

Examples:

// Filter the given array by removing single item
let web_lang = ["HTML", "CSS", "Javascript", "PHP", "SQL"];
let lang_to_remove = "SQL";
let filtered_langs = web_lang.filter(lang => lang !== lang_to_remove);

console.log(filtered_langs); // ["HTML", "CSS", "Javascript", "PHP"]

// Filter the given array by removing multiple items
let web_lang = ["HTML", "CSS", "Javascript", "PHP", "SQL"];
let langs_to_remove = ["PHP", "SQL"];
let filtered_langs = web_lang.filter(lang => !langs_to_remove.includes(lang));

console.log(filtered_langs); // ["HTML", "CSS", "Javascript"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. filter() method does not execute the function for array elements without values.
  2. filter() method does not change the original array.

  • findIndex() Method: This method returns the index of the first element in an array that pass a condition (provided as a function) and it returns -1 if it doesn't find any array element. Basically, it's very similar to find method, the only difference is, it returns the index instead of a value. ####Syntax:
array.findIndex(function(currentValue, index, arr), thisValue);
// function(currentValue, index, arr) is required but "thisValue" is optional. 
Enter fullscreen mode Exit fullscreen mode

Example:

let web_lang = ["HTML", "CSS", "Javascript", "PHP", "SQL"];
let lang_index = web_lang.findIndex(lang => lang === "Javascript");
    console.log(lang_index); // 2

let web_lang = ["HTML", "CSS", "Javascript", "PHP", "SQL"];
let lang_index = web_lang.findIndex(lang => lang === "Bootstrap");
    console.log(lang_index); // -1
Enter fullscreen mode Exit fullscreen mode

Notes: Both filter() and findIndex() methods does not execute the function for array elements without values and both does not change the original array.



3. Transforming Array Methods:

  • map(func) Method: This method creates a new array from results of calling function for every element.

Syntax:

array.map(function(currentValue, index, arr), thisValue);
// currentValue is a required parameter whereas index, arr and thisValue are optional.
Enter fullscreen mode Exit fullscreen mode

Example:

// Using regular function
let original_arr = [1, 2, 3, 4, 5];
let new_arr = original_arr.map(function(num){ 
    return num * 5;
});
    console.log(new_arr); // [5, 10, 15, 20, 25]

//Using arrow function
let original_arr = [1, 2, 3, 4, 5];
let new_arr = original_arr.map(num => num * 5);
    console.log(new_arr); // [5, 10, 15, 20, 25]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. This method neither execute the function for array elements without values nor change the original array.

  • sort(func) Method: This method sorts the items of an array either alphabetically or numerically, in either ascending(up) or descending(down) order and returns the sorted array.

Syntax:

array.sort([compareFunction]);
// compareFunction is an optional parameter. When it is not provided - all the array elements are converted to strings. 
Enter fullscreen mode Exit fullscreen mode

Example:

//Default behaviour 
let sort_array = ["d", "c", "b", "a"];
    sort_array.sort();
    console.log(sort_array); // ["a", "b", "c", "d"] (sorts alphabetically in ascending order)

let sort_array = [4, 3, 2, 1];
    sort_array.sort();
console.log(sort_array); // [1, 2, 3, 4] (sorts numerically in ascending order)

 // Using compareFunction
// Sort numbers in an array in ascending order:
// Using regular function
let scores = [5, 6, 1, 2, 4, 3];
scores.sort(function(x, y){return x-y});
console.log(scores); // [1, 2, 3, 4, 5, 6]

// Using arrow function 
let scores = [5, 6, 1, 2, 4, 3];
scores.sort((x, y) => x-y);
console.log(scores); // [1, 2, 3, 4, 5, 6]

// Sort numbers in an array in descending order:
// Using regular function
let scores = [5, 6, 1, 2, 4, 3];
scores.sort(function(x, y){return y-x});
console.log(scores); // [6, 5, 4, 3, 2, 1]

// Using arrow function
let scores = [5, 6, 1, 2, 4, 3];
scores.sort((x, y) => y-x);
console.log(scores); // [6, 5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. By default, the sort() method sorts the values as strings in alphabetical and ascending order.
  2. This method changes the original array.

  • reverse() Method: This method reverses the order of the elements in an array and then returns it.

Syntax:

array.reverse();
Enter fullscreen mode Exit fullscreen mode

Example:

let reverse_array = ["HTML", "CSS", "Javascript", "PHP", "SQL"];
    reverse_array.reverse();
    console.log(reverse_array); // ["SQL", "PHP", "Javascript", "CSS", "HTML"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. This method will change the original array.

  • split() Method: This method is used to split a string into an array of substrings, and returns the new array.

Syntax:

str.split();
Enter fullscreen mode Exit fullscreen mode

Example:

let string = "Coding is my passion!";
let split_string_into_words = string.split(" ");

console.log(split_string_into_words); // ["Coding", "is", "my", "passion!"]

let string = "Coding is my passion!";
let split_string_into_chars = string.split("");

console.log(split_string_into_chars); // ["C", "o", "d", "i", "n", "g", " ", "i", "s", " ", "m", "y", " ", "p", "a", "s", "s", "i", "o", "n", "!"]
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. The split() method does not change the original string.

  • join() Method: This method converts the elements of an array into a string. The elements will be separated by a specified separator. The default separator is comma (,).

Syntax:

array.join(separator);
// The separator is an optional. If omitted, the elements are separated with a comma(,).
Enter fullscreen mode Exit fullscreen mode

Example:

// Eg, join() method with no string passed. 
let array_strings = ["Coding", "is", "my", "passion"];
let join_strings = array_strings.join();

console.log(join_strings); // Coding,is,my,passion

// Eg, join() method with empty string but without space.
let array_strings = ["Coding", "is", "my", "passion"];
let join_strings = array_strings.join("");

console.log(join_strings); // Codingismypassion

// Eg, join() method with empty string but with a space. 
let array_strings = ["Coding", "is", "my", "passion"];
let join_strings = array_strings.join(" ");

console.log(join_strings); // Coding is my passion

// Eg, join() method with dash(-) string.
let array_strings = ["Coding", "is", "my", "passion"];
let join_strings = array_strings.join("-");

console.log(join_strings);// Coding-is-my-passion
Enter fullscreen mode Exit fullscreen mode

Notes: The join() method will not change the original array.



More methods will be added soon.....

Until then, Happy C❤️ding...

Top comments (0)