DEV Community

Giovanni Galiero
Giovanni Galiero

Posted on

1

Esplorare i Metodi degli Array di JavaScript: La Tua Guida Definitiva - Parte 1

Gli array di JavaScript sono uno strumento potente per la memorizzazione e la manipolazione dei dati. Ma con il potere arriva la complessità e può essere difficile sapere quale metodo degli array utilizzare per un dato compito.
In questo articolo, copriremo i migliori 5 metodi degli array di JavaScript in modo da poterli padroneggiare e portare le tue competenze di codifica al livello successivo.

javascript-array

1 .map()
Il metodo .map() crea un nuovo array chiamando una funzione fornita su ogni elemento dell'array originale. È un ottimo modo per trasformare un array di dati in una nuova forma.

Esempio:

_Example 1_
const numbers = [1, 2, 3, 4, 5]
// Use .map() to double each number
const doubledNumbers = numbers.map(num => num * 2)

console.log(doubledNumbers)
// Output: [2, 4, 6, 8, 10]

_Example 2_
const names = ['John', 'Jane', 'Jim']
// Use .map() to create an array of greetings
const greetings = names.map(name => `Hello, ${name}!`)

console.log(greetings)
// Output: ['Hello, John!', 'Hello, Jane!', 'Hello, Jim!']
Enter fullscreen mode Exit fullscreen mode

2 .filter()
Il metodo .filter() crea un nuovo array con tutti gli elementi che superano il test implementato dalla funzione fornita. È un ottimo modo per estrarre un sottoinsieme di dati da un array.

Esempio:

_Example 1_
const numbers = [1, 2, 3, 4, 5]
// Use .filter() to get all even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0)

console.log(evenNumbers) // Output: [2, 4]

_Example 2_
const words = ['dog', 'cat', 'elephant', 'bear', 'zebra'];
// Use .filter() to get all words with more than 3 letters
const longWords = words.filter(word => word.length > 3);

console.log(longWords); // Output: ['elephant', 'bear', 'zebra']
Enter fullscreen mode Exit fullscreen mode

3 .reduce()
Il metodo .reduce() applica una funzione su un accumulatore e su ogni elemento dell'array (da sinistra a destra) per ridurre l'array a un singolo valore. È un ottimo modo per eseguire operazioni su un array di dati e restituire un singolo risultato.

Esempio:

_Example 1_
const numbers = [1, 2, 3, 4, 5]
// Use .reduce() to find the sum of the numbers
const sum = numbers.reduce((acc, num) => acc + num, 0)

console.log(sum) // Output: 15

_Example 2_
const words = ['dog', 'cat', 'elephant', 'bear', 'zebra']
// Use .reduce() to concatenate all words into a sentence
const sentence = words.reduce((acc, word) => `${acc} ${word}`, '')

console.log(sentence) // Output: 'dog cat elephant bear zebra'
Enter fullscreen mode Exit fullscreen mode

4 .sort()
Il metodo .sort() ordina gli elementi di un array in loco e restituisce l'array ordinato. Per impostazione predefinita, ordina gli elementi in ordine crescente in base ai loro punti codice Unicode.

La funziona sort può restituire:

  • un valore negativo se a deve essere ordinato prima di b
  • zero (0) se a e b sono uguali
  • un valore positivo se a deve essere ordinato dopo b

Esempio:

_Example 1_
const numbers = [5, 2, 4, 1, 3]
// Use .sort() to sort the numbers in ascending order
const sortedNumbers = numbers.sort((a, b) => a - b)

console.log(sortedNumbers) // Output: [1, 2, 3, 4, 5]

_Example 2_
const words = ['zebra', 'dog', 'cat', 'bear', 'elephant']
// Use .sort() to sort the words in alphabetical order
const sortedWords = words.sort()

console.log(sortedWords) // Output: ['bear', 'cat', 'dog', 'elephant', 'zebra']
Enter fullscreen mode Exit fullscreen mode

5 .forEach()
Il metodo .forEach() esegue una funzione fornita una volta per ogni elemento dell'array. A differenza di .map() e .filter(), .forEach() non restituisce un nuovo array.

Esempio:

const numbers = [1, 2, 3, 4, 5]
// Use .forEach() to log each number
numbers.forEach(num => console.log(num))

// Output:
// 1
// 2
// 3
// 4
// 5

_Example 2_
const words = ['zebra', 'dog', 'cat', 'bear', 'elephant']

words.forEach((word, index) => {
  words[index] = word.charAt(0).toUpperCase() + word.slice(1)
})

console.log(words) // Output: ['Zebra', 'Dog', 'Cat', 'Bear', 'Elephant']
Enter fullscreen mode Exit fullscreen mode

Conclusioni
In conclusione, questi sono i migliori 5 metodi per gli array di JavaScript che dovresti padroneggiare. Che tu stia trasformando dati, estraendo un sottoinsieme, riducendo ad un singolo valore, ordinando o eseguendo un'azione, c'è un metodo adatto al compito.

Con questi strumenti nel tuo kit, sarai in grado di affrontare qualsiasi problema relativo agli array con facilità.

Buon coding! ✌️

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay