Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active November 4, 2021 11:00
Show Gist options
  • Save ross-u/97c39ea0a55ced695c0e1be8136ee5c6 to your computer and use it in GitHub Desktop.
Save ross-u/97c39ea0a55ced695c0e1be8136ee5c6 to your computer and use it in GitHub Desktop.
JS | Array methods - Summary

JS | Array methods - Summary


  • forEach() method executes a provided function once for each array element.
  • forEach() does not return a new array.
let arr = ['a', 'b', 'c'];

arr.forEach( function(element, index, originalArr) {
  console.log(element, index, originalArr);
});

// or in ES6
arr.forEach((element, index, originalArr) => console.log(element));

  • The map() method creates a new array with the results of calling a provided function on every element in the array.
  • map() always returns a new array.
  • map() doesn't mutate the original array, the original array is safe.

Example 1

const array = ['50', '60', '70'];

// ES5:
const newArray1 = array.map( function (number){
  return number * 2;
})
console.log(newArray);

// ES6:
const newArray2 = array.map( (number) => number * 2)
console.log(newArray);

Example 2

let students = [
  {firstName: 'John', lastName: 'Carr'},
  {firstName: 'Anna', lastName: 'Garcia'},
  {firstName: 'Sarah', lastName: 'Brown'},
]

let studentNames = students.map( function (element) {
    return element.firstName;
});

console.log(studentNames);

  • The filter() method creates a new array with the results that pass (true) the test implemented by the function.
  • filter() always returns a new array.
  • filter() doesn't mutate the original array, the original array is safe.

Example 1

const mixedArray = [10, '20', 30, '40', 50, '60', 70];

// ES5:
const numbers = mixedArray.filter( function (element){
  return typeof element === 'number';
})
console.log(numbers);

// ES6:
const numbers2 = mixedArray.filter((element) => {
  return typeof element === 'number';
})
console.log(numbers2);

  • The reduce() method is used to apply a function to each element in the array to reduce that array to a single value.
  • reduce() has an accumulator variable which is used to store things during the iterations and return something at the end.

Example 1

const array1 = [10, 19, 41, 30];

const reducedNumbers = array1.reduce( function (total, currentNum) {
    let updatedTotal = total + currentNum;
    return updatedTotal;
    // or return total + currentNum
}, 0);

Example 2

const listItems = [
  { name: 'Bob', age: 42},
  { name: 'Mark', age: 38}, 
  { name: 'Lea', age:21 },
  { name: 'Natalia', age:32 },
  { name: 'Anna', age:24 },
  { name: 'Stephen', age:25 }
];

const namesString = listItems.reduce( function (total, currentElement, index ) {
  let updatedTotal = total + ' ' + currentElement.name;
  return updatedTotal;
}, '');

reverse(), splice(), sort()

Note: reverse, splice and sort methods mutate/ change the original array.


  • reverse() method reverses an array in place.

  • The first array element becomes the last, and the last array element becomes the first.

  • reverse() mutates the original array. It reverses the array in place.

Example

const a = ['one', 'two', 'three'];
a.reverse();

console.log(a);  // ['three', 'two', 'one']

  • The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements

  • splice() method changes/mutates the original array.


const fruits = ["Apple", "Banana", "Pear", "Orange", "Coconut", "Mango", "Kiwi"];

// Removing elements from an array
const arr1 = fruits.splice(0,2);
console.log(arr1);

// Inserting new elements to an array
arr1.splice(1, 0, "Lemon", "Watermelon");
console.log(arr1);

  • sort() methods mutates the original array. It sorts an array in place.

  • At the end of sorting it returns only the reference to the original array, new array is not being created.

    This means that it sorts the array that calls the method, and returns the reference to that same array at the end.

  • sort() method sorts the array elements according to their string Unicode values - > Unicode Table. Therefore sorting of numbers is done in a different way (by providing the compare function).

  • Sorting of the numbers must be done with the compare function provided, to avoid numeric elements being sorted by their Unicode value.


Sorting Strings - works as expected

const fruits = ["Watermelon", "Banana", "Orange", "Apple", "Dragon Fruit", "Mango", "Cheries",];
fruits.sort();

Sorting Numbers - not correct by default

const numbers = [22, 23, 99, 68, 1, 0, 9, 112, 223, 64, 18];

numbers.sort();
console.log(numbers);
// Numbers are sorted according to their Unicode value
// [ 0, 1, 112, 18, 22, 223, 23, 64, 68, 9, 99 ]

Sorting the numbers - the right way ( using the compare function)

How does a sort() compare function work ?

  • compare function takes a pair of 2 elements on each iteration , argument a and argument b.
  • compare function should return either 0 , -1 or 1 . This returned value determines how a and b will be sorted.
  • 2 arguments ,a and b, can be named with a custom name e.g. str1 and str2.

compare function rules

  • If compareFunction(a, b) returns **-1 **, a is sorted before b ( leaves a to be first in the pair).

  • If compareFunction(a, b) returns 0, leave a and b unchanged.

  • If compareFunction(a, b) is greater than 0 ( 1 ), sort b to an index lower than a (i.e. bcomes first).

syntax

arr.sort(function compareFunction(a,b) {
	// order formula
});

Example

// sort ascending  .o:O
function compareAscending(a, b) {
  if ( a < b /* a is less than b by some ordering criterion */ ) {
    return -1;
  }
  if (a > b /* a is greater than b by the ordering criterion */ ) {
    return 1;
  }
  if (a == b /* a is equal to b */) {
    return 0;   
  }
}


// sort descending  O:o.
// Switch the comparison operators in the conditions
function compareDescending(a, b) {
  if ( a > b /* a is less than b by some ordering criterion */ ) {
    return -1;
  }
  if (a < b /* a is greater than b by the ordering criterion */ ) {
    return 1;
  }
  if (a == b /* a is equal to b */) {
    return 0;   
  }
}

sort() - shorthand

Sort numbers ascending - shorthand

// sort() acsending .o:0 - shorthand
const numbers = [22, 23, 99, 68, 1, 0, 9, 112, 223, 64, 18];

// ES5
numbers.sort(function(a, b) {
  return a - b;
});

// ES6
numbers.sort((a, b) => a - b);

Sort numbers descending - shorthand

// sort() descending O:o. - shorthand
const numbers = [22, 23, 99, 68, 1, 0, 9, 112, 223, 64, 18];

// ES5
numbers.sort(function(a, b) {
  return b - a;
});

// ES6
numbers.sort((a, b) => b - a);

Array - MDN documentation and reference

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