Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Mohamed-Code-309/4cfa323fd100c538b2c35939eb2cd9ca to your computer and use it in GitHub Desktop.
Save Mohamed-Code-309/4cfa323fd100c538b2c35939eb2cd9ca to your computer and use it in GitHub Desktop.

Exploring JavaScript's Array Methods: Mutated vs Non-Mutated Methods

The push() method adds one or more elements to the end of an array and returns the new length of the array.

var arr = ['a', 'b', 'c', 'd']
console.log(arr.push('e'));     //Output: 5 (new length of the array)
console.log(arr);   //Output: [ 'a', 'b', 'c', 'd', 'e' ]
//we can push multiple elements
var fruits = ["Banana", "Orange", "Apple", "Mango"];    
console.log(fruits.push("Kiwi", "Lemon", "Pineapple")); //Output: 7 
console.log(fruits);    //Output: ['Banana', 'Orange', 'Apple', 'Mango', 'Kiwi', 'Lemon', 'Pineapple']

Table of contents ☝️

The pop() method removes the last element from an array and returns that element. It changes the length of the array as well.

var arr = [1, 2, 3, 4, 5]
console.log(arr.pop());   //Output: 5 
console.log(arr);   //Output: [1, 2, 3, 4]

Table of contents ☝️

The shift() method removes the first element from an array and shifts all the other elements down by one index. It returns the removed element and changes the length of the array.

var arr = ['a', 'b', 'c'];
console.log(arr.shift());   //Output: 'a'
console.log(arr);   //Output: ['b', 'c']

Table of contents ☝️

The unshift() method adds one or more elements to the beginning of an array and shifts the existing elements up by one index. It returns the new length of the array.

var arr = ['a', 'b', 'c', 'd']
console.log(arr.unshift('e', 'f'));     //Output: 6 (length of the new array)
console.log(arr);     //Output: [ 'e', 'f', 'a', 'b', 'c', 'd' ]

Table of contents ☝️

The fill() method is used to fill (i.e., replace) all the elements of an array with a static value, from a start index to an end index. The method modifies the original array and returns the modified array.

The fill() method takes up to three arguments:

  • value (required):
    • The static value that will replace all the elements of the array.
  • start (optional):
    • The start index (position).
    • Default is 0.
  • end (optional):
    • The stop index (position)(won't be included).
    • Default is array length.
const arr1 = [1, 2, 3, 4, 5];
arr1.fill(0, 2, 4);
console.log(arr1); // Output: [1, 2, 0, 0, 5]

const arr2 = [1, 2, 3, 4];
arr2.fill(5, 1);
console.log(arr2); // Output: [1, 5, 5, 5]


const arr3 = [1, 2, 3, 4, 5];
arr3.fill(0);
console.log(arr3); // Output: [0, 0, 0, 0, 0]

Table of contents ☝️

The sort() method sorts the elements of an array in place - modify the original - and returns the sorted array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); //Output: [ 'Apple', 'Banana', 'Mango', 'Orange' ]

By default, the sort() function sorts values as strings, it casts elements to strings and compares their Unicode code points to determine the orders. Because of this, the sort() method will produce incorrect result when sorting numbers:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort();
console.log(numbers); //Output: [ 0, 1, 10, 2, 20, 3, 30 ]

In the previous example, since all the elements of the numbers array are numbers, they are first converted to strings and then sorted based on their Unicode code points. So the string '10' comes before the string '2' because the character '1' in 10 has a lower Unicode code point than the character '2'.

console.log('2'.charCodeAt(0));   //Output: 50
console.log('10'.charCodeAt(0));  //Output: 49

To fix this, you need to pass a compare function to the sort() method. The sort() method will use the compare function to determine the orders of elements.

array.sort(comparefunction)
//Sort ascending
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
console.log(points);  //Output: [ 1, 5, 10, 25, 40, 100 ]

In the compare function, a and b are variables that represent two elements of the array that need to be compared. If a is greater than b, the result of the subtraction will be positive and b will be moved to a lower index than a, and if a is less than b, the result of the subtraction will be negative and a will be moved to a lower index than b. If a and b are equal, the result of the subtraction will be 0 and their order in the sorted array will be determined by their original positions in the array.

To sort the array in descending order :

//Sort descending
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
console.log(points);  //Output: [ 100, 40, 25, 10, 5, 1 ]

Table of contents ☝️

The reverse() method allows you to modify an array by reversing the order of the elements in an array.

const arr = ['a', 'b', 'c', 'd', 'e'];
arr.reverse();
console.log(arr); // Output: ['e', 'd', 'c', 'b', 'a']

Table of contents ☝️

The splice() method allows you to modify an array by adding or removing elements from it and returns an array of the removed elements, if any.

array.splice(start, deleteCount, item1, ....., itemX)

The method has the following arguments:

  • start (required)
    • The index where the modification (add and/or remove) should begin.
  • deleteCount (optional)
    • Number of items to be removed
    • If this parameter is 0, no elements are removed
  • item1, item2, ..., itemX (optional)
    • Representing the elements to be added to the array, starting at the start index.
//Remove `Banana` from the array
var fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits.splice(0,1));    // Output: ["Banana"] 
console.log(fruits);    // Output: [ 'Orange', 'Apple', 'Mango' ] 

//Add `Lemon` to the array
console.log(fruits.splice(0,0,"Lemon"));  // Output: [] empty array as there is no item has been removed.
console.log(fruits);   // Output: [ 'Lemon', 'Orange', 'Apple', 'Mango' ] 
const fruits = ['apple', 'banana', 'cherry', 'dates'];

// remove 1 element at index 2
fruits.splice(2, 1);
console.log(fruits); // Output: ['apple', 'banana', 'dates']

// remove 2 elements starting at index 1 and add two elements
fruits.splice(1, 2, 'mango', 'orange');
console.log(fruits); // Output: ['apple', 'mango', 'orange']

// add three elements starting at index 1 without removing any elements
fruits.splice(1, 0, 'kiwi', 'grape', 'pineapple');
console.log(fruits); // Output: ['apple', 'kiwi', 'grape', 'pineapple', 'mango', 'orange']

Table of contents ☝️

The copyWithin() method is used to copy a portion of an array to another location in the same array, overwriting its original values. The method does not add items to the array or modifying array length.

arr.copyWithin(target, start, end)

The method takes three arguments:

  • target (required)
    • the index where the copied elements should be placed.
  • start (optional)
    • The index where the copying should begin.
    • Element at the specified index will be included.
    • If not provided, it defaults to 0.
  • end (optional)
    • the index where the copying should end.
    • Element at the specified index will not be included.
    • If not provided, it defaults to the length of the array.
// Copy the first two array elements starting from index 2
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.copyWithin(2, 0, 2);
console.log(fruits); // Output: [ 'Banana', 'Orange', 'Banana', 'Orange', 'Kiwi' ]
// copy the first two elements starting from index 3
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(3, 0, 2);
console.log(arr);   // Output: [1, 2, 3, 1, 2]
// section of the array starting from index 3 will be copied and pasted starting from index 1
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.copyWithin(1, 3); 
console.log(arr);   // Output: [ 'a', 'd', 'e', 'd', 'e' ]
//overwrite elements starting from index 2 by copying the elements starting from index 0 to the end  
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
fruits.copyWithin(2);
console.log(fruits); // Output: [ 'Banana', 'Orange', 'Banana', 'Orange', 'Apple' ]

Table of contents ☝️

The at() method is used to retrieve an element from an array at a specified index. This method is similar to the traditional bracket notation ([]) used to access array elements.

The at() method takes a single argument, which is the index of the element you want to retrieve. If the index is negative, it counts from the end of the array. If the index is greater than or equal to the length of the array, it returns undefined.

const arr = ['a', 'b', 'c', 'd', 'e'];

console.log(arr.at(2));   // 'c'
console.log(arr.at(-1));  // 'e'
console.log(arr.at(5));   // undefined

Table of contents ☝️

The indexOf() method returns the first index at which a given element can be found in an array. The method returns -1 if the element is not found.

const fruits = ['apple', 'banana', 'orange', 'pear', 'apple'];

const index1 = fruits.indexOf('apple');
console.log(index1); //Output: 0

const index2 = fruits.indexOf('lemon'); 
console.log(index2);  //Output: -1

The indexOf() method takes an optional second parameter which specifies the starting index for the search. By default, the search starts from the beginning of the array, but you can specify a different starting index by passing it as the second parameter. For example:

const fruits = ['apple', 'banana', 'orange', 'pear', 'apple'];
const index = fruits.indexOf('apple', 1); //start searching from index 1 instead of index 0.
console.log(index); //Output: 4

Table of contents ☝️

The lastIndexOf() method works similarly to indexOf(), but it returns the last index at which a given element can be found in an array, or -1 if it is not present.

const fruits = ['apple', 'banana', 'orange', 'pear', 'apple'];
const lastIndex = fruits.lastIndexOf('apple');
console.log(lastIndex);  //Output: 4

Similarly, for lastIndexOf(), the search starts from the end of the array by default, but you can specify a different starting index by passing it as the second parameter. For example:

const fruits = ['apple', 'banana', 'orange', 'pear', 'apple'];
const lastIndex = fruits.lastIndexOf('apple', 3);
console.log(lastIndex);  //Output: 0

Table of contents ☝️

The find method is used to find the first element in an array that matches a given condition (provided as a function), and returns that element. If no element matches the condition, find returns undefined.

const numbers = [1, 2, 3, 4, 5];
const result = numbers.find(num => num > 3);

console.log(result); // Output: 4

Table of contents ☝️

The findIndex() method is used to find the index of the first element in an array that satisfies a given condition (provided as a function). If no element in the array satisfies the condition, the method returns -1

const numbers = [2, 5, 7, 9, 12];
const index = numbers.findIndex(element => element > 7);
console.log(index)  //Output: 3 (corresponding to the element 9)

Table of contents ☝️

The filter method is used to create a new array containing all elements that match a given condition (provided as a function). if no element matches the condition, filter will return an empty array [].

const numbers = [1, 2, 3, 4, 5];
const result = numbers.filter(num => num > 3);

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

Table of contents ☝️

The includes() method tests whether an array includes a specific element or value, and returns a boolean value of true or false.

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const hasBanana = fruits.includes('banana');
console.log(hasBanana); // Output: true

You can also provide a second parameter to the includes() method to specify the search index at which to start the search. For example:

const fruits = ['apple', 'banana', 'orange', 'kiwi'];
const hasKiwi = fruits.includes('banana', 2);
console.log(hasKiwi); // Output: false

In the previous example, the includes() method returns false because the fruits array doesn't contains the string 'banana' starting from the index 2 (which is the third element in the array). If we modify the search index in the includes method to start from 0 or 1 or omit it at all, the method would have returned true.

Table of contents ☝️

The every() method tests whether all elements in an array pass a given condition, and returns a boolean value of true or false. The method accepts a callback function that is executed once for each array element. The method returns true if the function returns true for all of the array elements and returns false if the function returns false (and stops) for one element and it does not execute the function for empty array.

//check if all the elements in the array is greater than zero
const numbers = [3, 7, 9, 10, 15];
const allPositive = numbers.every((number) => number > 0);

console.log(allPositive); // Output: true
//check if all the elements in the array is greater than 20
function isBigEnough(element) {
    return element >= 20;
}
console.log([20, 25, 19, 30, 44].every(isBigEnough)); // Output: false (cause of 19)

Table of contents ☝️

The some() method tests whether at least one element in an array passes a given condition, and returns a boolean value of true or false.

The method accepts a callback function that is executed once for each array element. The method returns true (and stops) if the function returns true for one of the array elements and returns false if the function returns false for all of the array elements and it does not execute the function for empty array.

var ages = [22, 27, 18, 25, 15];
var result = ages.some(function (element) { return element < 20 });
console.log(result);    //Output: true (cause 18 was found)
//check if all elements in the array are even
const numbers = [3, 7, 9, 5, 15];
const hasEven = numbers.some((number) => number % 2 === 0);
console.log(hasEven); // Output: false

Table of contents ☝️

The concat() method is used to merge/join two or more arrays into a new array and it does not modify the original array.

array1.concat(array2, array3, ..., arrayX)
//array1 remain unchanged
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9];

const newArray = array1.concat(array2, array3);
console.log(newArray);  // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array1);    // Output: [1, 2, 3]

Table of contents ☝️

The slice() method is used to extract a section/portion of an array and return a new array without modifying the original array.

array.slice(start, end)

The slice() method takes two optional parameters: start and end:

  • start (optional):
    • The index to start extracting from.
    • Element at the specified index will be included.
    • If not provided, slice() will start at index 0.
  • end (optional):
    • The index to end extracting.
    • Element at the specified index will not be included.
    • If not provided, slice() will extract until the end of the array.
const arr = [1, 2, 3, 4, 5];

const section1 = arr.slice(1, 4);
console.log(section1); // Output: [2, 3, 4]

//return the whole array starting from index 2
const section2 = arr.slice(2);
console.log(section2); // Output: [3, 4, 5]
const arr = [1, 2, 3];

//use slice to get the last element with Destructuring Assignment
const [last] = arr.slice(-1);
console.log(last);  // Output: 3

//create new copy of the array (shallow copy) that share another memory reference
const arr2 = arr.slice();
arr2.push(4);
console.log(arr);   // Output: [1, 2, 3]
console.log(arr2);  // Output: [1, 2, 3, 4]
/*
NOTE: arr2 = arr1 : 
- will make both arrays have the same memory reference
- modifying one of them will directly affect the other
*/

Table of contents ☝️

The flat() method is used to flatten an array array by recursively flattening nested arrays, in other words, reduce the nesting of an array.

This method accepts a single parameter that specifies how deep the nested array should be flattened. If no argument is provided, it defaults to a depth of 1. If the depth is set to Infinity, the method will recursively flatten all nested arrays.

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());   // [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));  // [0, 1, 2, Array [3, 4]]

const arr3 = [0, 1, 2, [[[[3, [[4, 5]], 6]]]]];
console.log(arr3.flat(Infinity)); // [0, 1, 2, 3, 4, 5, 6]

Table of contents ☝️

The map() method is used to create a new array with the results of calling a provided function on every element in the original array.

//Multiply all the values in an array with 10:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) {
  return num * 10;
}
console.log(newArr);    //Output: [ 650, 440, 120, 40 ]
//Return a new array with the square root of all element values:
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt);
console.log(newArr);    //Output: [ 2, 3, 4, 5 ]
//create a new array contains the squared values of all elements:
const numbers = [1, 2, 3, 4, 5];
const newArr = numbers.map(number => number * number);
console.log(newArr);    //Output: [ 1, 4, 9, 16, 25 ]

map() returns a new array with the same length as the original array, where each element is the result of applying the provided function to the corresponding element in the original array. It can be very useful when you want to transform an array of values in some way, without modifying the original array.

Table of contents ☝️

The flatMap() method is the combination of the map() method followed by the flat() method of depth 1. flatMap() first maps each element in the array to a new array by calling a provided function, and then flattens the resulting array into a single array.

const numbers = [[1, 2], [3, 4], [5, 6]];
const flattenedNumbers = numbers.flatMap(array => array.map(number => number * 2));
console.log(flattenedNumbers);  //Output: [ 2, 4, 6, 8, 10, 12 ]
const words = ['hello', 'world'];

const letters = words.map(word => word.split(''));
console.log(letters);   //Output: [ [ 'h', 'e', 'l', 'l', 'o' ], [ 'w', 'o', 'r', 'l', 'd' ] ]

const flattenLetters = words.flatMap(word => word.split(''));
console.log(flattenLetters);   //Output: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

Table of contents ☝️

The reduce() method executes a reducer function for array element. The reducer function iterate over the array and accumulate a single value based on the elements in the array. The reduce() method returns a single value: the function's accumulated result at the end of iteration.

The reduce() function has the following syntax:

array.reduce(callback, initialValue)

Here, callback is a function that takes two arguments: an accumulator and the current value being processed. The initialValue parameter is optional, and represents the initial value of the accumulator.

During each iteration, the callback function is called with the current accumulator value and the current element of the array. The callback function should return a new accumulator value, which will be passed to the next iteration. The final value of the accumulator is returned after the last iteration.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
/**
 * 1st iteration:   0 (initialValue) + 1(first element) = 1
 * 2nd iteration:   1 + 2  = 3
 * 3rd iteration:   3 + 3  = 6
 * 4th iteration:   6 + 4  = 10
 * 5th iteration:   10 + 5 = 15 (final result)
 */

In the previous example, reduce() is used to accumulate the sum of all the numbers in the numbers array. The callback function takes two arguments, an accumulator (sum) and the current value being processed (currentValue).

In each iteration, the currentValue is added to the sum, which is then returned as the new accumulator value. The initialValue parameter is set to 0, so the sum starts at 0.

Table of contents ☝️

reduceRight() is a variant of the reduce() method that works similarly but processes the elements of the array from right to left instead of from left to right. The basic syntax for reduceRight() is the same as for reduce():

array.reduceRight(callback, initialValue)
const numbers = [2, 45, 30, 100];
const subtract = numbers.reduceRight(getSum);
function getSum(total, num) {
    return total - num;
}

console.log(subtract);  //Output: 23
/**
 * 1st iteration:   100 - 30 = 70
 * 2nd iteration:   70 - 45  = 25
 * 3rd iteration:   25 - 2   = 23 (final result)
 */

Table of contents ☝️

The join() method creates and returns a new string by concatenating all of the elements in an array and make them separated by commas or a specified separator string.

//default separator (comma)
const arr1 = ["apple", "banana", "orange"];
const str1 = arr1.join(); // "apple,banana,orange"

//custom separator 1
const arr2 = ["red", "green", "blue"];
const str2 = arr2.join("-"); // "red-green-blue"

//custom separator 2
const arr2 = ["good", "bad", "ugly"];
const str2 = arr2.join("/"); // "good/bad/ugly"

//undefined and null converted to an empty string
const arr3 = ["apple", 42, true, undefined, null];
const str3 = arr5.join(); // "apple,42,true,,"

Table of contents ☝️

The toString() method returns a string with array elements separated by commas.

const arr = [1, 2, 3];
const str = arr.toString(); // "1,2,3"

Table of contents ☝️

toLocaleString() is similar to toString()in converting the array elements into strings separated by commas. The main difference between them is that toLocaleString() returns a string that represents the elements of the array using localized conventions, such as using the appropriate date and time formats or number formats for a given locale.

const arr = [new Date(), 1234.56, "hello"];
const str = arr.toLocaleString(); 
// "3/3/2023, 1:23:45 PM, 1,234.56, hello"
// the output may vary depending on the user's settings and location

The following examples showing how to pass locales and options parameters in the toLocaleString() method.

const arr = [new Date(2023, 2, 3), 1234.56];
const options = { year: "numeric", month: "long", day: "numeric" };
const str = arr.toLocaleString("en-US", options); 
// "March 3, 2023, 1,234.56"
let prices = [689, 100, 4577, 56];

// using United States Dollar currency string format
let str = prices.toLocaleString("en-US", {
  style: "currency",
  currency: "USD",
});
console.log(str); //$689.00,$100.00,$4,577.00,$56.00
const arr = [1234.56, 7890.12];
const options = { style: "currency", currency: "EGP" };
const str = arr.toLocaleString("ar-EG", options); 
// "١٬٢٣٤٫٥٦ ج.م.‏، ‎٧٬٨٩٠٫١٢ ج.م.‏"

Table of contents ☝️

Related Content:

✔️ Top 13 Javascript Interview Questions You Should Answer !
✔️ Exploring the Power of map() and reduce() functions in JavaScript (coming soon)
✔️ How to Easily Manipulate and Transpose Arrays of Objects in JavaScript (coming soon)

Links:

🕴️ Linkedin: Dragon Slayer 🐲
📝 Articles: All Articles written by D.S

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment