DEV Community

Cover image for Almost Everything I Need To Know About Arrays In Javascript Using Crypto As Examples
API crud
API crud

Posted on

Almost Everything I Need To Know About Arrays In Javascript Using Crypto As Examples

Arrays in JavaScript are a way to store multiple values in a single variable. They are incredibly useful for handling lists or collections of data. In this tutorial, we'll explore arrays using examples related to blockchain and cryptocurrencies.

Creating an Array

To create an array, you can use square brackets []. Each item in the array is separated by a comma.

let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano"];
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Cardano"]
// or let cryptocurrencies = new Array ("Bitcoin", "Ethereum", "Cardano");
Enter fullscreen mode Exit fullscreen mode

Array Type Checking

To check if a variable is an array

console.log(Array.isArray(cryptocurrencies)); // true
Enter fullscreen mode Exit fullscreen mode

Length

The length property returns the number of elements in an array.

console.log(cryptocurrencies.length); // 3
Enter fullscreen mode Exit fullscreen mode

Accessing Array Elements

You can access an element in an array by referring to its index number. Array indexes start from 0.

console.log(cryptocurrencies[0]); // Outputs: Bitcoin
Enter fullscreen mode Exit fullscreen mode

indexOf

Finds the index of an element in the array.

let index = cryptocurrencies.indexOf("Ethereum");
console.log(index); // 1
Enter fullscreen mode Exit fullscreen mode

Modifying an Array

You can modify an existing array by accessing an index and assigning a new value.

cryptocurrencies[2] = "Solana";
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Solana"]
Enter fullscreen mode Exit fullscreen mode

Adding Elements to an Array

JavaScript arrays have various methods to add new elements. push() adds an element at the end of the array.

cryptocurrencies.push("Litecoin");
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Solana", "Litecoin"]
Enter fullscreen mode Exit fullscreen mode

unshift() adds an element at the start of the array

cryptocurrencies.unshift("Cardano");
console.log(cryptocurrencies); // ["Cardano", "Bitcoin", "Ethereum", "Solana", "Litecoin"]
Enter fullscreen mode Exit fullscreen mode

Removing Elements from an Array

The pop() method removes the last element from an array.

let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
cryptocurrencies.pop();
console.log(cryptocurrencies); // Outputs: ["Bitcoin", "Ethereum", "Cardano"]
Enter fullscreen mode Exit fullscreen mode

shift() Removes the first element from an array.

cryptocurrencies.shift(); // Removes "Bitcoin"
// Outputs: ["Ethereum", "Cardano"]
Enter fullscreen mode Exit fullscreen mode

Creating new array from another

slice() Returns a new array containing a portion of the original array.

let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
console.log(cryptocurrencies.slice(0, 2));
// Array["Bitcoin", "Ethereum"]
console.log(cryptocurrencies.slice(1, 3));
// Expected output: Array["Ethereum", "Cardano"]
Enter fullscreen mode Exit fullscreen mode

Changing Contents Of An Array

splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place

let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
// Inserts at index 1
cryptocurrencies.splice(1, 0, "Binance");
console.log(cryptocurrencies)
// Array["Bitcoin", "Binance", "Ethereum", "Cardano", "Solana"]
// Replaces 1 element at index 4
cryptocurrencies.splice(4, 1, "Dogecoin");
console.log(cryptocurrencies)
// Expected output: Array["Bitcoin", "Binance", "Ethereum", "Cardano", "Dogecoin"]
Enter fullscreen mode Exit fullscreen mode

Iterating Over Arrays

You can loop over an array using a for loop or forEach method.

Example with for loop:

let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
for(let i = 0; i < cryptocurrencies.length; i++) {
    console.log(cryptocurrencies[i]);
    // Expected outputs in order: "Bitcoin", "Ethereum", "Cardano", "Solana"
}
Enter fullscreen mode Exit fullscreen mode

Example with forEach:

cryptocurrencies.forEach(crypto => {
    console.log(crypto);
    // Expected outputs in order: "Bitcoin", "Ethereum", "Cardano", "Solana"
});
Enter fullscreen mode Exit fullscreen mode

Example with map:

let lengths = cryptocurrencies.map(function(item) {
    return item.length;
});
console.log(lengths); // [7, 8, 7, 6]

Enter fullscreen mode Exit fullscreen mode

filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(function(number) {
    return number % 2 === 0;
});
console.log(evenNumbers); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

reduce()

The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

Syntax

let result = array.reduce(function(accumulator, currentValue, currentIndex, array) {
    // return result from performing operation
}, initialValue);
Enter fullscreen mode Exit fullscreen mode

*accumulator: Accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
*currentValue: The current element being processed in the array.
*currentIndex (optional): The index of the current element being processed in the array.
*array (optional): The array reduce was called upon.
*initialValue (optional): A value to use as the first argument to the first call of the callback.

The sum of all numbers in an array:

let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, currentValue) {
    return accumulator + currentValue;
}, 0);

console.log(sum); // 15
Enter fullscreen mode Exit fullscreen mode

Spread Operator

Combine two arrays

let cryptocurrencies = ["Bitcoin", "Ethereum", "Cardano", "Solana"];
let numbers = [1, 2, 3, 4, 5, 6]
let combined = [...cryptocurrencies, ...numbers];
console.log(combined); // ["Bitcoin", "Ethereum", "Cardano", "Solana", 1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Converting Arrays To Strings Using join()

let currencyString = cryptocurrencies.join(", ");
console.log(currencyString); // "Bitcoin", "Ethereum", "Cardano", "Solana"
Enter fullscreen mode Exit fullscreen mode

Practical Exercise

  1. Create an array named blockchains with elements "Ethereum", "Binance Smart Chain", and "Cardano".
  2. Add "Polkadot" to the end of the blockchains array.
  3. Replace "Binance Smart Chain" with "Solana".
  4. Use a loop to print each element of the blockchains array.

Arrays are a fundamental part of JavaScript and mastering them is crucial for any aspiring developer. So remember to practise.

Did I miss out any knowledge about Arrays? Let me know in the comments. Thanks.

Top comments (0)