ARRAY IN JAVASCRIPT
Through objects, we can store values that are accessed with the corresponding key. However, we often need to store an ordered set of values to do this we use arrays. In Javascript, arrays as well as functions are objects, and since they are adjectives we can add properties.
METHODS ON ARRAYS
The code below illustrates, as mentioned in the introduction, that arrays are also objects.
CONSTRUCTOR FUNCTION ARRAY
We see from the figure below that in the prototype of the constructor function Array there are many methods for working with arrays; therefore, before writing a function it is good to make sure that one does not already exist.
SOME ARRAY METHODS
Let us begin by viewing through the code below some of the common array methods.
MAP METHOD OF PROTOTYPE
When we need to perform an operation for each element in an array, we can use the map method. The map method can be very useful when we have an array of objects and want to retrieve the value of a particular key.
FILTER METHOD
When we want to create an array with the filtered elements from another array, we use the filter method. The difference from map is that the callback passed as input must return true or false. If it returns true that element is inserted into the new array and vice versa.
REDUCE METHOD
The reduce method reduces all elements of an array to a single value. The callback is a little different, it receives as its first value an accumulator i.e. the returned elements and as its second value the current value of the iterated array.
SPLICE METHOD
With splice we can insert, remove or replace elements of an array. The first parameter is the start index, with the second we indicate how many elements we want to delete in the case of elimination, and from the third element onwards how many we want to add.
SORT METHOD
To sort an array we have at our disposal the sort method. sort converts elements to string and performs a Unicode comparison of 16-bit units.
FILL METHOD
The fill method modifies an array by assigning a specific value to one or all of the elements.
EVERY AND SOME METHODS
With some we can check whether at least one element of an array passes a check. For example, we want to know whether an element of an array is value two. With the every method we want to know whether all the elements of an array pass one of our checks.
FROM METHOD OF ARRAY
The array.from method creates an object from an array like.
MAKE A DEEP COPY
The code below illustrates how to make a deep copy of an array (Deep Copy).
DEEPENING AI
Array.prototype.map()
Description
The map() method is one of the most widely used and versatile methods for working with arrays in JavaScript. It allows you to iterate over each element of an array and transform it into something new, returning a new array of equal length. Each element of the original array is passed to a function that performs the transformation, and the result of that function is inserted into the new array.
Main features:
-Does not modify the original array; always creates a new array.
-The length of the new array is always the same as that of the original array.
-It is immutable: the original array is not altered.
-It is commonly used when you want to transform an array without directly mutating it.
Syntax
const nuovoArray = array.map((elementoCorrente, indice, array) => {
// Trasformazione dell’elemento corrente
return nuovoElemento;
});
–elementoCorrente: Each element of the array during iteration.
-index: (optional) The index of the current element.
-array: (optional) The original array being iterated over.
-Returns: A new array with the result of the transformation for each element.
Basic example.
Suppose you have an array of numbers and want to get a new array that contains twice as many of each number:
const numeri = [1, 2, 3, 4];
const doppi = numeri.map(num => num * 2);
console.log(doppi); // [2, 4, 6, 8]
In this case, for each number in the array, the num * 2 function is applied and the result is added to the new array.
Function with multiple parameters
You can also use the index or the original array in the callback function to have more control:
const numeri = [1, 2, 3, 4];
const conIndici = numeri.map((num, index) => num * index);
console.log(conIndici); // [0, 2, 6, 12]
Here the function multiplies each number by its index in the array.
Example with objects
If you have an array of objects and want to transform one of their fields, map() is extremely useful. For example:
const utenti = [
{ nome: ‘Mario‘, età: 30 },
{ nome: ‘Giulia‘, età: 25 },
{ nome: ‘Luca‘, età: 40 }
];
const nomi = utenti.map(utente => utente.nome);
console.log(nomi); // [‘Mario’, ‘Giulia’, ‘Luca’]
Here a new array containing only the names of the utenti is created.
Chaining
map() can be combined with other array methods such as filter() or reduce() to perform more complex operations in a single chain. For example:
const numeri = [1, 2, 3, 4, 5, 6];
const quadratiPari = numeri
.filter(num => num % 2 === 0) // Filtra i numeri pari
.map(num => num ** 2); // Eleva al quadrato i numeri pari
console.log(quadratiPari); // [4, 16, 36]
In this example, first the array is filtered to get only the even numbers and then they are squared.
Differences with forEach()
Although forEach() may look similar to map(), there are some important differences:
-forEach(): executes a function for each element but returns nothing.
-map(): executes a function on each element and returns a new array with the results.
Example with forEach():
const numeri = [1, 2, 3];
numeri.forEach(num => console.log(num * 2)); // Stampa: 2, 4, 6
// Ma non restituisce un nuovo array.
Performance
map() is generally efficient, but it always creates a new array in memory. If you do not need a new array, and you just want to iterate and perform an action on each element, it is more suitable to use forEach().
Conclusions
The map() method is an extremely powerful tool for transforming arrays in JavaScript in a functional way, while maintaining the immutability of the original array. It is especially useful when working with transformed data or wanting to create a different representation of the elements of an array.
Array.prototype.reduce()
Description
The reduce() method in JavaScript allows you to iterate over an array, executing a callback function on each element to reduce the array to a single value. This method is particularly useful for performing cumulative or aggregation operations, such as summing all elements of an array, calculating averages, concatenating strings, or constructing objects.
Key features:
-Reduces an array to a single value (which can be a number, object, string, array, or other).
-Can be initialized with an optional initial value.
-Does not modify the original array.
-Offers great flexibility because the accumulator can be of any type (number, array, object, etc.).
Syntax
const risultato = array.reduce((accumulatore, elementoCorrente, indice, array) => {
// Operazione di riduzione
return nuovoAccumulatore;
}, valoreIniziale);
–accumulatore: The cumulative value resulting from the previous iterations. During the first iteration, it is equal to the valueInitial if supplied.
–elementoCorrente: The array element on which the function is currently operating.
–indice (optional): The current index of the element in the array.
–array (optional): The original array on which it is iterating.
–valoreIniziale (optional): The value with which you are starting the reduction operation. If omitted, the accumulatore initially takes the value of the first element in the array, and the iteration starts from the second element.
Basic example.
Imagine you have an array of numbers and you want to sum all its elements:
const numeri = [1, 2, 3, 4];
const somma = numeri.reduce((acc, num) => acc + num);
console.log(somma); // 10
In this case, the initial value is 1 (the first element of the array) and the iteration starts from the second element (2).
Example with objects
reduce() can be used to create objects or perform complex aggregations. Suppose we have an array of user objects and we want to count how many of them are older than 30:
const utenti = [
{ nome: ‘Mario‘, età: 32 },
{ nome: ‘Giulia‘, età: 25 },
{ nome: ‘Luca‘, età: 40 }
];
const numeroDiAdulti = utenti.reduce((acc, utente) => {
if (utente.età > 30) {
acc += 1;
}
return acc;
}, 0);
console.log(numeroDiAdulti); // 2
In this example, reduce() adds 1 to the accumulator whenever a user is older than 30.
Example of string concatenation
reduce() can also be used to concatenate strings. For example, we can join all the words in a sentence:
const parole = [‘Reduce‘, ‘è‘, ‘un‘, ‘metodo‘, ‘potente‘];
const frase = parole.reduce((acc, parola) => acc + ‘ ‘ + parola);
console.log(frase); // “Reduce è un metodo potente”
Nested Arrays (Flattening)
A common use of reduce() is flattening nested arrays (nested arrays):
const arrayAnnidato = [[1, 2], [3, 4], [5, 6]];
const arrayPiatto = arrayAnnidato.reduce((acc, curr) => acc.concat(curr), []);
console.log(arrayPiatto); // [1, 2, 3, 4, 5, 6]
Here, reduce() is used to concatenate the internal arrays into a single flat array.
Advanced example: Creating an object from an array
Suppose we have an array of key-value pairs and we want to transform it into an object:
const coppie = [[‘nome‘, ‘Mario‘], [‘età‘, 30], [‘città‘, ‘Roma‘]];
const oggetto = coppie.reduce((acc, [chiave, valore]) => {
acc[chiave] = valore;
return acc;
}, {});
console.log(oggetto); // { nome: ‘Mario’, età: 30, città: ‘Roma’ }
In this example, reduce() transforms an array of key-value pairs into an object.
Differences with other methods
-map(): map() creates a new array by transforming each element of an array, but does not reduce it to a single value as reduce() does.
-filter(): filter() creates a new array with only some elements based on a condition, while reduce() can combine or transform elements into a single result.
-forEach(): forEach() performs a function for each element, but returns nothing; reduce(), on the other hand, returns a single value.
Performance
reduce() may be less efficient than simpler methods such as forEach() or map() for operations on large arrays, since it involves a callback function for each iteration. However, for cumulative or complex operations (such as transforming an array into an object), it is one of the most powerful tools in JavaScript.
Conclusion
The reduce() method is a powerful tool for performing complex transformations and cumulative operations on arrays in JavaScript. It is very flexible and can be used to reduce an array to a single value of any type, providing detailed control over how the elements are combined.
Array.prototype.fill()
-Description: The fill() method fills all elements of an array from a beginning index to a final index with a static value.
-Use: It is used to overwrite the elements of an array with a specific value.
-Syntax:
array.fill(valore, inizio, fine);
-Example:
const numeri = [1, 2, 3, 4];
numeri.fill(0, 1, 3); // [1, 0, 0, 4]
Array.prototype.splice()
-Description: The splice() method modifies the contents of an array by removing, replacing or adding elements.
-Use: It is used to directly manipulate the contents of an array.
-Syntax:
array.splice(indiceInizio, numeroElementiDaRimuovere, elementoDaAggiungere1, elementoDaAggiungere2, …);
-Example:
const numeri = [1, 2, 3, 4];
numeri.splice(1, 2, 5, 6); // [1, 5, 6, 4]
Array.prototype.filter()
-Description: The filter() method creates a new array with all the elements that pass the test implemented by the provided function.
-Use: It is used to create a subset of an array based on a condition.
-Syntax:
const nuovoArray = array.filter((elementoCorrente, indice, array) => {
return condizione;
});
•Example:
const numeri = [1, 2, 3, 4];
const numeriGrandi = numeri.filter(num => num > 2); // [3, 4]
Array.prototype.sort()
-Description: The sort() method sorts the elements of an array locally and returns the sorted array. The default is to sort the elements as strings.
-Use: It is used to sort an array, with a custom criterion if necessary.
-Syntax:
array.sort((a, b) => {
// comparazione
return a – b;
});
•Example:
const numeri = [4, 2, 3, 1];
numeri.sort((a, b) => a – b); // [1, 2, 3, 4]
Array.prototype.every()
-Description: The every() method checks whether all elements of an array satisfy a certain condition. It returns true if the condition is met for all elements, otherwise false.
-Use: It is used to check whether all elements of an array satisfy a condition.
-Syntax:
const tuttiVerificati = array.every((elementoCorrente, indice, array) => {
return condizione;
});
•Example:
const numeri = [2, 4, 6];
const tuttiPari = numeri.every(num => num % 2 === 0); // true
Array.prototype.some()
-Description: The some() method checks whether at least one element of the array satisfies a given condition. It returns true if at least one element satisfies the condition, otherwise false.
-Use: It is used to check whether there is at least one element that satisfies a condition.
-Syntax:
const almenoUno = array.some((elementoCorrente, indice, array) => {
return condizione;
});
•Example:
const numeri = [1, 2, 3];
const haPari = numeri.some(num => num % 2 === 0); // true
Leave A Comment