Published on

Implementing Arrays with NodeJS and Javascript

Authors
  • avatar
    Name
    Jonathan Juliani
    Twitter

Arrays, The Basic Data Structure

data-structures-arrays

Arrays, or simply lists, are the basics and considered in my opinion the foundation for developing and starting to know about data structures. They help organize, process and analyze data, so to make it easier, think of arrays as boxes that can store a variaty of items, where you can easily access, add or remove any of these items.

They are useful for dealing with collections of data in your applications. Exploring the use of arrays can really improve the quality and efficiency of your code.

Arrays: The Foundation

The Basic: Understanding Arrays

An array is an ordered or unordered collection of elements, which can be of any type, from numbers and strings to objects and even other arrays. In NodeJS/JavaScript, and other languages, arrays are very flexible and can help you solve a lot of problems, you will use them many times.

implementing-arrays-with-nodejs-javascript

Let's Create an Array in NodeJS/Javascript

A criação de um array em Node/JavaScript é muito simples, podendo ser iniciado vazio ou já com elementos. Acessar e modificar seus elementos é igualmente direto, utilizando índices que começam em zero.

Creating an array in Node/JavaScript is very simple, it can be started with an empty array or a already fulfilled array with element(s). Accessing and modifying it's elements is equally straightforward, using indexes that start at zero.

const frutas = ['Apples', 'Bananas', 'Oranges']
const frutasQueJonGosta = [] // empty array

console.log(frutas[0])
// shold print: Apples

Array with objects:

const fulano = {
  nome: 'fulano',
  idade: 99,
}

const beltrano = {
  nome: 'beltrano',
  idade: 98,
}

const pessoas = [fulano, ciclano]

console.log(pessoas[0])
// shold print: { "nome": "fulano", "idade": 99 }

Some Useful Array Functions

Within Node.JS/JavaScript arrays come with some built in methods/functions that facilitate operations such as adding or removing elements (push, pop, shift, unshift, among others), iterate through elements (forEach, map, filter), and much more. Let's see a summary of some here?!

push: Adds one or more elements to the end of an array and returns the new length of the array.

const arr = [1, 2, 3]
arr.push(4)
// arr now is [1, 2, 3, 4]

pop: Removes the last element from an array and returns the removed element.

const arr = [1, 2, 3]
const poppedElement = arr.pop()
// arr now is [1, 2] and the pop element is 3

shift: Removes the first element from an array and returns the removed element.

const arr = [1, 2, 3]
const shiftedElement = arr.shift()
// arr now is [2, 3] and the shifted element is 1

unshift: Adds one or more elements to the beginning of an array and returns the new length of the array.

const arr = [2, 3]
arr.unshift(1)
// arr now is [1, 2, 3]

map: Executes a callback function on each element of the array and returns a new array with the results.

Pro tip: if you don't need a new array with the results, then you don't need to use map, use forEach.

const numbers = [1, 2, 3]
const doubled = numbers.map((num) => num * 2)
// doubled now is [2, 4, 6]

filter: Returns a new array with all elements that passed the test implemented by the callback function.

const numbers = [1, 2, 3, 4, 5]
const evenNumbers = numbers.filter((num) => num % 2 === 0)
// evenNumbers now is [2, 4]

forEach: Executes a callback function on each element of the array, it doesn't return anything, it just does what you're asking :)

const numbers = [1, 2, 3]
numbers.forEach((num) => console.log(num))
// prints: 1 2 3

Jon, we missed reduce, includes, find, findIndex, concat, slice, splice…

There are many functions built in for arrays in NodeJS/Javascript and of course in other programming languages, if you want a simple explanation like the ones above about these functions too, let me know in the comments bellow and I'll create another post just about functions in arrays, the idea here was to give you a brief summary on what you can do with arrays.

Beyond the Basics

Managing Collections

Arrays are fundamental in for managing collections, allowing you to filter, sort and map data sets efficiently. This capability is essential for dealing with data from databases, files, or APIs.

Other Data Structures and Algorithms

Arrays are generally the base for other complex data structures such as stacks and queues. Furthermore, they are fundamental in sorting and search algorithms.

Best Practices

Efficiency with Arrays

Para garantir um código limpo e eficiente, sabe quando outra pessoa for mexer? Devemos fazer um código fácil pra que a outra pessoa entenda, que seja um código de fácil manutenção, então cuida pra utilizar métodos de array de forma clara, prefira const para arrays que não serão reatribuídos, e aproveita os métodos mais recentes do ES6+, como map, reduce, e filter para operações imutáveis.

imutáveis: Jon, vc disse que vai explicar as coisas de forma simples.

Certo, imutável é quando você não vai mudar o conteúdo do array. Por exemplo, quando você usa o map, você executa uma função para cada item do array, e recebe um novo array de volta, você não altera o array anterior, ou seja, foi uma operação imutável, você não alterou a origem da informação.

To ensure clean and efficient code, we must make sure our code is easy for the other people to understand, that the code is easy to maintain, so use array methods clearly, prefer const for arrays that will not be reassigned, and take advantage of the latest ES6+ methods, such as map, reduce, and filter for immutable operations.

immutable: Jon, you said you will explain things in a simpler way no buzzwords.

Right, immutable is when you won't change the contents of the array. For example, when you use map, you are executing a function for each item inside or the original array, but you receive a new array back, you do not change the original one, that is an immutable operation, you did not change the source of the information.

Em Resumo: A Versatilidade Insuperável dos Arrays

Arrays são, sem dúvida, uma das estruturas de dados mais versáteis e poderosas não só em JavaScript e Node.js mas em qualquer outra linguagem. Dominá-los é essencial para qualquer desenvolvedor pra criação de aplicações e pra solução de problemas com outras estruturas também.

Você tem alguma dica, truque ou pergunta sobre o uso de arrays em JavaScript/Node.js? Qual função dos arrays você mais usa? Compartilha aí e vamos aprender juntos!

In Summary Arrays are Powerful Tools

Arrays are, without a doubt, one of the most versatile and powerful data structures not only in JavaScript and Node.js but in many other programming languages. Mastering them is essential for any developer to create applications and solve problems, even problems with other data structures.

Do you have any tips, tricks, or questions about using arrays in JavaScript/Node.js? Which array function do you use most? Share it and let's learn together!