BackButton

Ruby/ JavaScript Iterating Cheat Sheet

Methods for Arrays

Multi-Dimensional Array Method

#transpose

When called on an a 2D-array, transpose changes the columns to rows.

a = [[1,2], [3,4], [5,6]] a.transpose
#=> [[1, 3, 5], [2, 4, 6]]

Extra: Access a column by selecting the value at each index you specify.

each {|x| x.values_at(0)}

Methods for +/- elements

#pop

#push

#slice

Methods for sorting elements

#sort

#reverse

Accumulator/ Counter methods

#inject

#reduce

Description: Shortcut methods to avoid creating a counting variable.

Change Each

#map

Definition: Perform an action on each item, output new array that is the result of the code block.

a = [ "Hello", "Bye" ]
a.map { |word| word + "!" }
#=> ["Hello!", "Bye!"]

Methods for Hashes

Looping through Keys & Values

#each_key

#each_pair

#each_value

Key-Value Conditionals

#has_key?

#has_value?

Methods for Both

Act on each element

#each

Use index to get values

#values

#values_at()

Conditional Method

#include?

Groups Based on a Filter Condition

#select, #collect, #reject

Note: collect is not a hash method.

Nested Data Structures

Access Literally

Array Example:

array[1][1][2][0]

(Index position in square brackets)

vs.

Hash Example:

hash[:outer][:inner]["almost"][3]

(key or value in square brackets)

Access by Looping

#each

For a multi-dimensional array:

array.each do |element|
element.each {|sub_element|
#codeblock
}
end

Looping in JavaScript

Looping Through Everything in an Object

for...in

for...of

for var..; range; increment

Looping through Conditionally

while

do...while