HomeAbout

Array Methods

Chaining Methods

Prefer chaining methods back to back than creating new every transformation

const newArr = []; newArr .filter(x => x === true) .map(el => el)

Cheatsheet

/* Modifers */ arr.shift() // remove first; return removed element arr.unshift() // add to first; return new length of array arr.pop() // remove last; return removed element arr.push() // add to end; return new length of array /* Filter => shallow copy; original unmodified */ const filteredItems = items.filter( item => { return item.price <= 100; }); /* Map => shallow copy; original unmodified */ const items = [1,2,3]; const itemNames = items.map( item => { return item + 1; }); // [2,3,4] /* Find => first matching element */ const foundItem = items.find( item => { return item.name === "book"; }); /* FindIndex => index of first matching element; when no match, return -1 */ const array = [1,2,3]; const found = array.findIndex( item => { return item > 2; }); console.log(found); // 2 /* IndexOf => returns int */ const beasts = ["ant", "bison", "camel", "duck", "bison"]; beasts.indexOf("bison"); // 1 beasts.indexOf("giraffe"); // -1 // Start from index 2 beasts.indexOf("bison", 2); // 4 /* Slice => returns shallow copy (new array); does not modify original */ const animals = ["ant", "bison", "camel", "duck", "elephant"]; // start only animals.slice(2); // ["camel", "duck", "elephant"] // start and end (end index is excluded) animals.slice(2, 4); // ["camel", "duck"] // last n-number of elements animals.slice(-2); // ["duck", "elephant"] /* Splice => returns remove item in array format; modified original */ array.splice(start_index, deleteCount, item_to_add, another_add) // when adding at a start_index, old element becomes start_index+1 /* Sort => returns reference to same array; modifies original */ const months = ["March", "Jan", "Feb", "Dec"]; months.sort(); console.log(months); // ["Dec", "Feb", "Jan", "March"] /* Includes => boolean for whether array contains a value */ const items = [1,2,3]; const includesTwo = items.includes(2); // true /* Some => returns boolean for whether ANY ONE element is matching */ const items = [1]; const expensiveItem = items.some( item => { return item <= 100; }); // true /* Every => returns boolean of whether every single item meets the condition */ const lessThanHundred = items.every( item => { return item < 100; }); /* Reversed => returns reversed array; modifies original also */ const array1 = ["one", "two", "three"]; const arr2 = array1.reverse(); /* Join => returns string */ const elements = ["Fire", "Air", "Water"]; elements.join(); // "Fire,Air,Water" elements.join(""); // "FireAirWater" elements.join("-"); // "Fire-Air-Water" /* forEach => undefined */ items.forEach( item => { console.log(item.name); }); /* Reduce */ const total = items.reduce( (carryover, item) => { return item.price + carryover; }, 0); // 0 is the starting value

.forEach()

forEach method calls a function once for each element in array in order

const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // a b c

Example of Creating New Modified Array

const numbers = [1,2,3]; const newNumbers = []; numbers.forEach((x) => newNumbers.push(x*2)); console.log(newNumbers); // [2,4,6]

Chaining indexOf() and forEach() to remove duplicates from Array

function removeDup(arr) { const result = []; // iterate through passed array, check if the index is its first occurence of item arr.forEach((item, index) => { if (arr.indexOf(item) == index) { result.push(item) } }); return result }

.from()

Static method creates a new, shallowed-copied Array instance from an iterable or array-like object

  • Iterable
    • e.g. Map, Set
  • Array-like object
    • objects with a length property and indexed elements
/* String iterated as array */ Array.from('foo'); // ["f", "o", "o"] /* Array iterated and modified */ Array.from([1, 2, 3], (x) => x*2); // [2, 4, 6]

Async iterables

When dealing with async iterables, use Array.fromAsync()

.isArray()

Determines whether the passed value in an array in boolean

Array.isArray([1, 2, 3]) // true Array.isArray({foo: 123}) // false Array.isArray('foobar') // false Array.isArray(undefined) // false

.join()

creates and returns a new string by concatenating all of the elements in the array

const elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // "Fire,Air,Water" console.log(elements.join('')); // "FireAirWater" console.log(elements.join('-')); // "Fire-Air-Water" console.log(elements.join(', ')); // "Fire, Air, Water"

.length()

returns number of elements in an array

x = ["one", "two"].length; // 2

Accessing last element

let lastIndex = array.length-1; let lastElement = array[lastIndex];

.some()

Tests whether at least one element in the array passes the test implemented by the provided function

  • returns boolean
  • it does not modify the array
const array = [1, 2, 3, 4, 5]; // Checks whether an element is even const isEven = (el) => el % 2 === 0; array.some(isEven); // true
AboutContact