Arrays

An array is an object which stores an ordered collection of values. This can hold values of any data type (numbers, strings, objects, functions, or other arrays), storing them in a single variable.

  • We declare an array as a variable, using the [] characters and inside the items separated with commas

let fruits = ["apple", "banana", "cherry"]; // Declaring an array
let diversity = ["apple", 2, {}, 4.21]; // An array with different elements
let numbers = new Array(1, 2, 3, 4); // Using the Array constructor
let empty = []; // An empty array

print(fruits) //The are printed entirely

  • The elements in an array can be accessed using indexes (positions), determined by integer numbers that start at 0. We use the name of the variable and the index value between the [] characters. Each element can also be stored in other variables.

let days = ["monday","tuesday","wednesday", "thursday"]
console.log(days[0])     // This prints "monday"

let second = days[2]; // Storing a element in a variable
console.log(second)     //  This prints "wednesday"

  • If we access a position that is outside the length of the array, we will get a undefined value. Also, if we assign a value to a position out of index, this will create empty spots in the array

let days = ["monday","tuesday","wednesday", "thursday"];
console.log(days[1]);    // This prints "tuesday"
console.log(days[9]);     // This prints undefined

let arr = [];
a[5] = 42;    // Assign value out of index
console.log(arr); // This prints [5 empty items, 42 ]

  • We can update any element of an array by assigning a new value to the objective index. This works even if the array was declared as a constant, but the entire array can't be reassigned

const days = ["monday","tuesday","wednesday", "thursday"]
console.log(days)     // This prints the original array
days[3] = "newItem";
console.log(days)     // This prints the modified array

  • The length attribute is crucial for working with an array, indicating the number of elements that the array stores.

let days = ["monday","tuesday","wednesday", "thursday"]
console.log(days.length) // This prints 4

  • The push() method lets us add items to the end of the array or in a specific position. In the same way, the pop() method removes the item in the last position

let days = ["monday","tuesday","wednesday", "thursday"]
days.push("friday")
days.push("saturday", "sunday") // We cna add multiples items at time
console.log(days) // This prints the array with the new items

days.pop() // Remove last item
console.log(days) // This prints the array with the removed item

  • There are a lot of other useful array methods. Some examples are:

let fruits = ["apple", "banana", "cherry"];
fruits.shift()	// Remove and return first item	
fruits.unshift("kiwi") // Add item to start
fruits.splice(1, 0, "pear") // Add or remove at specific position. We specify how many items to remove with the second parameter
let newFruits = fruits.slice(1, 3) // Copy a portion of the array. This has to be assigned to a variable. The second parameter value excludes that index.
fruits.indexOf("banana") // Get the first index of an element
fruits.includes("apple")    // Checks if value exists
fruits.join(", ") // Join elements into string. We indicate the separator used between each value
fruits.reverse()    //Reverse the order of the array
fruits.sort()	// Sort the array by ASCII

  • Arrays can also be nested to contain other arrays, and in the same the indexes are nested to access elements inside arrays of arrays

let arrOfArr = [[1,2,3],["a","b","c"]]; // An array of arrays
console.log(arrOfArr[0]) // This prints the whole first array
console.log(arrOfArr[1][2]) // This prints the third element of the second array

Iterators

Iterators are the built-in JavaScript array methods that help us iterate over the elements of an array. They are methods called on arrays to manipulate elements and return values.

  • We can traverse all elements in an array with loops

let fruits = ["Mango", "Lemon", "Pineapple"]
for (let i = 0; i < fruits.length; i++){ // Using length value and simple for loop
  console.log(fruits[i]);
}

for (let fruit of fruits){ // Using a for-of loop
  console.log(fruit);
}

  • Using .forEach() will execute the same code for each element of the array. This just use the elements and returns undefined when finished

let fruits = ["Mango", "Lemon", "Pineapple"]
fruits.forEach(fruit => { // Run a function for each item
  console.log(fruit);
});
fruits.forEach(f => console.log("Fruit: " + f)) /

function printFruit(element){ // Defining function to then call it
  console.log(element);
}

fruits.forEach(printFruit); // Calling the defined callback function

  • Using .map() will create a new array by transforming each item with a function. It works like .forEach(), but has to be assigned to a variable to save the resultant array

let fruits = ["Mango", "Lemon", "Pineapple"]
let upper = fruits.map(f => {
    return f.toUpperCase(); // Create new array by transforming each item
});
console.log(upper)

  • Using .filter() returns an array of elements after filtering out certain elements based on the callback function that verifies a statement that returns true or false depending on the element. Those that return true, are added to the new array, and if there isn’t any element that satisfies the condition, the function will return an empty array

let fruits = ["Mango", "Lemon", "Pineapple"]
let shortFruits = fruits.filter(f => {
    return f.length < 6  // Create new array with only items passing a condition
});
console.log(shortFruits)

let noFruits = fruits.filter(f => {
    return f.length > 100  // This return and empty array
});
console.log(noFruits)

  • Using .findIndex() will return the index of the first element that evaluates to true in the callback function. If there isn’t any element that satisfies the condition, the function will return -1

let fruits = ["Mango", "Lemon", "Pineapple"]
let long = fruits.findIndex(f => {
    return f.length == 5 // Return the index of the first element found
});
console.log(long)

let noOne = fruits.findIndex(f => {
    return f.length > 100 // This returns -1
});
console.log(noOne)

  • Using .reduce() returns a single value after iterating through the elements of an array, in other words, accumulates a value based on every element of an array. In the callback function, the first parameter is an accumulator variable, and the second one is the iterator. It can also take an optional second parameter to set an initial value for the accumulator

let numbers = [1, 2, 4, 6, 8, 10];
let sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue  // Acumulating the values
});
console.log(sum) // This prints 31

let sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue  // Acumulating the values
}, 100); // Initial value for acummulator
console.log(sum) // This prints 131

  • Using .some() returns true if there is at least one element of an array that passes a condition, otherwise it returns false

let numbers = [1, 2, 4, 6, 8, 10];
let yes = numbers.some( num => {
  return num > 5  // Check if the condition is passed by any value
});
console.log(yes) // This prints true

let no = numbers.some( num => {
  return num > 15  // This condition is not passed by any value
});
console.log(no) // This prints false

  • Using .every() returns true if every element of an array passes a condition, otherwise it returns false

let numbers = [1, 2, 4, 6, 8, 10];
let yes = numbers.every( num => {
  return num > 0  // Check if the condition is passed by every value
});
console.log(yes); // This prints true

let no = numbers.every( num => {
  return num > 1  // This condition is not passed by the first value
});
console.log(no); // This prints false

Last updated