Skip to content

Instantly share code, notes, and snippets.

@0bie
Last active September 21, 2022 17:42
Show Gist options
  • Save 0bie/622391af97c61bc30cfbe56d187b259d to your computer and use it in GitHub Desktop.
Save 0bie/622391af97c61bc30cfbe56d187b259d to your computer and use it in GitHub Desktop.
Array Methods

Array Methods

join():
  • Converts all the elements of an array to strings and concatenates them
  • Returns the resulting string
const a = [1, 2, 3];
a.join(); // => "1,2,3"
a.join(' '); // => "1 2 3"
a.join(', '); // => "1, 2, 3"
a.join(''); // => "123"
const b = new Array(10) // => An array of length 10 with no elements
b.join('-') // => '---------' string of 9 hyphens
reverse():
  • Reverses the order of elements of an array.
  • reverse() doesn't create a new array with the elements rearranged but instead rearranges them in the already existing array
const a = [1, 2, 3];
a.reverse(); // => [3, 2, 1]
sort():
  • Sorts the elements of an array and returns the sorted array

  • When no arguments are passed it sorts in alphabetical order

  • undefined elements are sorted to the end of the array

  • sort() also accepts a comparison function as an argument. This function determines which of the two arguments should appear first in the sorted array

  • sort() modifies the existing array on which it is invoked

let a = ['banana', 'cherry', 'apple'];
a.sort();
const s = a.join(', '); // => s == "apple, banana, cherry"

// Numerical sort
let a = [33, 4, 1111, 222];
a.sort(); // => Alphabetical order: 1111, 222, 33, 4
a.sort((a, b) => a - b); // => Numerical order: 4, 33, 222, 1111
a.sort((a, b) => b - a); // => Reverse numerical order: 1111, 222, 33, 4

// Case insensitive alphabetical sort
let a = ['ant', 'Bug', 'cat', 'Dog'];
a.sort(); // => case-insensitive sort: ['Bug', 'Dog', 'ant, 'cat']
a.sort((s, t) => {
  // convert strings to lower case
  const a = s.toLowerCase();
  const b = t.toLowerCase();
  // compare strings
  // if the first arg should appear before the second the function should return a value less than zero
  // if the second arg should appear before the first the function should return a value greater than zero
  // if both values are equal (order is irrelevant) the function should return zero
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
});

// Output: ['ant', 'Bug', 'cat', 'Dog']
concat():
  • Creates and returns a new array that contains the elements of the original array on which concat() was invoked, followed by each of the args passed to concat()

  • If any of these args is itself an array, then it is the array elements that are concatenated, not the array itself.

  • concat() doesn't modify the array on which it is invoked

let a = [1, 2, 3];
a.concat(4, 5); // => [1, 2, 3, 4, 5]
a.concat([4, 5]); // => [1, 2, 3, 4, 5]
a.concat([4, 5], [6, 7]); // => [1, 2, 3, 4, 5, 6, 7]
a.concat(4, [5, [6, 7]]); // => [1, 2, 3, 4, 5, [6, 7]]
slice():
  • Returns a subarray of the specified array on which slice() was invoked

  • It accepts two args that specify the start and end of the subarray to be returned

  • The subarray contains the element specified by the first arg and all subsequent elements up to but not including the element specified by the second arg

  • If only one arg is passed the subarray contains all elements from the start position to the end of the array

  • An arg of -1 specifies the last element in the array, and an arg of -3 specifies the third from last element in the array

  • slice() doesn't modify the array on which it is invoked

  • The count is based on the index of the array elements so it starts at 0 (like usual)

let a = [1, 2, 3, 4, 5];
a.slice(0, 3); // => [1, 2, 3]
a.slice(3); // => [4, 5]
a.slice(1, -1); // => [2, 3, 4]
a.slice(-3, -2); // => [3]
splice():
  • Used to insert and remove elements from an array

  • splice() modifies the array on which it is invoked

  • Elements of the array that come after the insertion or deletion point have their indexes increased or decreased

  • splice() accepts 2 args:

    • The first arg specifies the array position where the insertion or deletion starts.

    • the 2nd arg specifies the number of elements that should be deleted from (spliced out of) the array.

  • If the 2nd arg is omitted all elements from the start position to the end of the array are removed

  • splice() returns an array of the deleted elements, or an empty array if no elements were deleted

const a = [1, 2, 3, 4, 5, 6, 7, 8];
a.splice(4); // => [5, 6, 7, 8]
a; // => [1, 2, 3, 4]
a.splice(1, 2); // => [2, 3]
a; // => [1, 4]
a.splice(1, 1); // => [4]
a; // => [1]
  • The first 2 args may be followed by any number of additional args that specify elements to be inserted into the array, starting at the position specified by the first arg.
const a = [1, 2, 3, 4, 5];
a.splice(2, 0, 'a', 'b'); // => []
a; // => [1, 2, 'a', 'b', 3, 4, 5]
a.splice(2, 2, [1, 2], 3); // => ['a', 'b']
a; // => [1, 2, [1, 2], 3, 3, 4, 5]
  • splice() inserts arrays themselves, not the elements of those arrays
push() and pop():
  • push() and pop() allow you to work with arrays as if they're stacks

  • push() appends one or more new elements to the end of an array and returns the new length of the array

  • pop() deletes the last element of an array, decrements the array length, and returns the element that it removed

  • Both methods modify the array on which they are invoked

const stack = [];
stack.push(1, 2); // => 2
stack; // => [1, 2]
stack.pop(); // => 2
stack; // => [1]
stack.push(3); // => 2
stack; // => [1, 3]
stack.pop(); // => 3
stack; // => [1]
stack.push([4, 5]); // => 2
stack; // => [1, [4, 5]]
stack.pop(); // => [4, 5]
stack; // => [1]
stack.pop() // => 1
stack; // => []
unshift() and shift():
  • Similar to push() and pop(), the major difference is that they insert and remove elements from the beginning of an array rather than from the end.

  • unshift() adds an element (or elements) to the beginning of an array, shifts the existing array elements up to higher indexes to make room, and returns the new length of the array

  • shift() removes and returns the first element of the array, shifting all subsequent elements down one place to occupy the newly vacant space at the start of the array

const a = [];
a.unshift(1); // => 1
a; // => [1]
a.unshift(22); // => 2
a; // => [22, 1]
a.shift(); // => 22
a; // => [1]
a.unshift(3, [4, 5]); // => 3
a; // => [3, [4, 5], 1]
a.shift(); // => 3
a; // => [[4, 5], 1]
a.shift() // => [4, 5]
a; // => [1]
a.shift() // => 1
a; // => []
toString():
  • Converts each of its elements to a string and outputs a comma separated list of those strings
[1, 2, 3].toString(); // => "1,2,3"
['a', 'b', 'c'].toString(); // => "a,b,c"
[1, [2, 'c']].toString(); // => "1,2,c"
forEach():
  • Iterates through an array, invoking a function you specify for each element

  • forEach() invokes a function with three args: the value of the array element, the index of the array element, and the array itself.

  • forEach() modifies the array on which it is invoked

const data = [1, 2, 3, 4, 5];
let sum = 0;

data.forEach((value) => sum += value);
sum; // => 15

data.forEach((v, i, a) => a[i] = v + 1);
data; // => [2, 3, 4, 5, 6]
map():
  • Passes each element of the array on which it is invoked to the function you specify, and returns an array containing the values returned by that function.

  • map() doesn't modify the array on which it is invoked but rather returns a new array

const a = [1, 2, 3];
const b = a.map((x) => x * x);
b; // => [1, 4, 9]
filter():
  • Returns an array containing a subset of the elements of the array on which it is invoked.

  • The function passed to filter should return either true or false and it is invoked on each element of the array, similar to forEach() and map()

  • If the return value is true (or a value that converts to true), then the element passed to the function is a member of the subset and is added to the new array that will be returned.

const a = [5, 4, 3, 2, 1];
smallValues = a.filter((v) => v < 3 ); // => [1, 2]
reduce() and reduceRight():
  • reduce() and reduceRight() combine the elements of an array, using the function you specify to produce a single value.
const a = [1, 2, 3, 4, 5];
const sum = a.reduce((x, y) => x + y);
sum; // => 15
const product = a.reduce((x, y) => x * y);
product; // => 120
const max = a.reduce((x, y) => (x > y) ? x : y);
max; // => 5
  • reduceRight() works similar to reduce(), the major difference is that it processes the array from highest index to lowest (right to left)
indexOf() and lastIndexOf():
  • Search an array for an element with a specified value, and return the index of the first such element found, or -1 if none is found.

  • indexOf() searches the array from beginning to end, and lastIndexOf() searches from end to beginning.

  • Both methods accept one or more args; the first arg specifies the value to search for while the 2nd arg specifies the index to start the search from. If no 2nd arg is passed it searches the entire array

  • If the 1st arg doesn't exist in the array it returns a value of -1.

var a = [0, 1, 2, 1, 0];
a.indexOf(1); // => 1
a.lastIndexOf(1) // => 3
a.indexOf(3) // => -1
from():
  • Create a new Array instance form an array-like or iterable object
function sort() {
  var a = Array.from(arguments);
  return a.sort();
}

sort(40, 20, 50, 30); // => [20, 30, 40, 50]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment