APIcrud

Tutorials, source codes and solutions on React, Next.js, Vercel, AWS and more

Want to take your web development skills to the next level and build a SaaS app? Follow me to build fast and learn how to balance between technical debt, delivery speed to launch quickly and validate early. Let's network and learn together!

Brought to you by AdrianteoycLinkedin

A Simple Guide To JavaScript Array Methods

Introduction

In this tutorial, we will explore essential JavaScript array methods: filter, map, reduce, sort, forEach, find, some and every, splice, and concat to demonstrate their usage with examples related to blockchain and cryptocurrency data.

  1. filter
    The filter method allows you to create a new array containing elements that satisfy a specified condition. In the context of blockchain and cryptocurrency data, you might want to filter out transactions or addresses based on specific criteria.
    In this example, we filtered transactions sent by the address '0xABC'.
const transactions = [
  { sender: "0xABC", amount: 10 },
  { sender: "0xDEF", amount: 20 },
  { sender: "0xABC", amount: 15 },
];

const filteredTransactions = transactions.filter(
  (transaction) => transaction.sender === "0xABC"
);
console.log(filteredTransactions);
  1. map
    The map method allows you to create a new array by applying a function to each element of an existing array. You can use it to transform blockchain or cryptocurrency data in various ways.
    Here, we converted prices from USD to EUR using a conversion rate of 0.85.
const pricesInUSD = [100, 200, 300];
const pricesInEUR = pricesInUSD.map((priceUSD) => priceUSD * 0.85);
console.log(pricesInEUR);
  1. reduce
    The reduce method is used to reduce an array to a single value by applying a specified function to each element. It can be handy for calculating totals, averages, or finding maximum/minimum values in cryptocurrency data.
    In this example, we calculated the total transaction amount.
const amounts = [10, 20, 15];
//array.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue,);
const totalAmount = amounts.reduce((acc, amount) => acc + amount, 0);
console.log(totalAmount);
  1. sort
    The sort method arranges the elements of an array in a specified order. You can use it to sort cryptocurrency data based on different attributes like date, price, or transaction volume.
    Here, we sorted cryptocurrencies by price in descending order.
const cryptoPrices = [
  { name: "Bitcoin", price: 45000 },
  { name: "Ethereum", price: 3000 },
  { name: "Ripple", price: 1.5 },
];

cryptoPrices.sort((a, b) => b.price - a.price); // Sorting by descending price
console.log(cryptoPrices);
  1. Compare
    While not a built-in method, you can use custom comparison functions with methods like sort or filter to perform more complex comparisons in your blockchain or cryptocurrency data.
    In this example, we sorted transactions by transaction amount using a custom comparison function.
function compareTransactions(transactionA, transactionB) {
  return transactionA.amount - transactionB.amount;
}

const sortedTransactions = transactions.slice().sort(compareTransactions);
console.log(sortedTransactions);
  1. forEach:
    Iterates over each element in an array and executes a function on each of them.
    In this example, we iterate through cryptocurrency transactions and log each transaction's sender and amount.
const cryptocurrencyTransactions = [
  { sender: "0xABC", amount: 10 },
  { sender: "0xDEF", amount: 20 },
  { sender: "0xGHI", amount: 15 },
];

cryptocurrencyTransactions.forEach(function (transaction) {
  console.log(
    `Transaction from ${transaction.sender}: ${transaction.amount} units`
  );
});
  1. find
    The find method in JavaScript is handy for searching through an array of cryptocurrency data and returning the first element that satisfies a specified condition. This can be especially useful when you need to locate a specific transaction, address, or data point in your cryptocurrency data.
    In this example, we search for a specific cryptocurrency address and display its balance when found.
const cryptocurrencyAddresses = [
  { address: "0xABC", balance: 1000 },
  { address: "0xDEF", balance: 500 },
  { address: "0xGHI", balance: 1500 },
];

const targetAddress = "0xDEF";

const foundAddress = cryptocurrencyAddresses.find(function (address) {
  return address.address === targetAddress;
});

console.log(
  `Address: ${foundAddress.address}, Balance: ${foundAddress.balance} units`
);
  1. some and every
    Check if some or all elements in an array of cryptocurrency data satisfy a condition.
    In this example, we use some to check if there are any high-value transactions and every to validate if all transactions have valid sender addresses.
const cryptocurrencyTransactions = [
  { sender: "0xABC", amount: 10 },
  { sender: "0xDEF", amount: 20 },
  { sender: "0xGHI", amount: 15 },
];

const isAnyHighValue = cryptocurrencyTransactions.some(function (transaction) {
  return transaction.amount > 20;
});

const areAllTransactionsValid = cryptocurrencyTransactions.every(function (
  transaction
) {
  return transaction.sender.startsWith("0x");
});

console.log(`Any high-value transactions: ${isAnyHighValue}`);
console.log(`All transactions valid: ${areAllTransactionsValid}`);
  1. splice
    Adds or removes elements from an array of cryptocurrency data.
    In this example, we remove and add cryptocurrency transactions using the splice method.
const cryptocurrencyTransactions = [
  { sender: "0xABC", amount: 10 },
  { sender: "0xDEF", amount: 20 },
  { sender: "0xGHI", amount: 15 },
];

// Removing the second transaction
cryptocurrencyTransactions.splice(1, 1);

console.log(cryptocurrencyTransactions);

// Adding a new transaction at index 1
const newTransaction = { sender: "0xXYZ", amount: 25 };
cryptocurrencyTransactions.splice(1, 0, newTransaction);

console.log(cryptocurrencyTransactions);
  1. concat
    Combines two or more arrays of cryptocurrency data. In this example, we combine two arrays of cryptocurrency addresses into a new array named combinedAddresses using the concat method.
const cryptocurrencyAddresses1 = [
  { address: "0xABC", balance: 1000 },
  { address: "0xDEF", balance: 500 },
];

const cryptocurrencyAddresses2 = [
  { address: "0xGHI", balance: 1500 },
  { address: "0xJKL", balance: 2000 },
];

const combinedAddresses = cryptocurrencyAddresses1.concat(
  cryptocurrencyAddresses2
);

console.log(combinedAddresses);

Conclusion

JavaScript array methods are powerful tools for manipulating and processing blockchain and cryptocurrency data. By mastering methods like filter, map, reduce, sort, and custom comparison functions, you can efficiently work with these datasets and create dynamic applications in the world of cryptocurrencies and blockchain technology. Hope you like this article and practise well. Thanks.