Skip to content

JavaScript Collections

Vojtech Mašek edited this page Aug 19, 2019 · 2 revisions

JavaScript Collections

Prerequisites

  • arrow functions (MDN)
  • template string literals (MDN)

Loops

for-in Loop

Iterates over objects' enumerable keys.

const object = {flow: 'up', hello: 'world', foo: 'bar'};
for (const key of object) {
  console.log(key, object[key]);
}
/*  flow up
    hello world
    foo bar     */

for-of Loop

Iterates over objects that implement the iteration protocol.

// iteration over an array's elements
for (const value of array) { …… }

// iteration over an array's index/value pairs
for (const [index, value] of array.entries()) { …… }

// iteration over an object's keys
for (const key of Object.keys(object)) { …… }

Functional-style Array Methods

Mapping and filtering

<array>.map((element, index, <array>) => ……)

Returns a new array of the same length where callback(oldArray[n], n, oldArray) === newArray[n] for every n-th element of the original array.

> ['yolo', 'swag', 'cajk'].map((item, index) => `${index + 1}. ${item.toUpperCase()}`)
['1. YOLO', '2. SWAG', '3. CAJK']

<array>.filter((element, index, <array>) => ……)

Returns a new array of lower or equal length containing every element of the original array for which the callback returns a truthy value.

> ['lorem', 'ipsum', 'dolor', 'sit', 'amet'].filter(item => item.indexOf('m') !== -1)
['lorem', 'ipsum', 'amet']

Aggregation

<array>.every((element, index, <array>) => ……)

Returns true if the callback returns a truthy value for every element of the array, false otherwise.

<array>.some((element, index, <array>) => ……)

Returns true if the callback returns a truthy value for at least one element of the array, false otherwise.

<array>.find((element, index, <array>) => ……)

Returns the first element of the array for which the callback returns a truthy value, undefined otherwise.

<array>.findIndex((element, index, <array>) => ……)

Returns the index of the first element of the array for which the callback returns a truthy value, -1 otherwise.

<array>.reduce((accumulator, element, index, <array>) => ……, first)

First sets the accumulator to first, then iterates over the array passing its elements and the current accumulator to the callback and updating the accumulator with the callback's return value. Return the accumulator after

Clone this wiki locally