Skip to content

Latest commit

 

History

History
774 lines (591 loc) · 24.4 KB

05_day_arrays.md

File metadata and controls

774 lines (591 loc) · 24.4 KB

30 Days Of JavaScript: Arrays

Twitter Follow

Autore: Asabeneh Yetayeh
Gennaio, 2020

<< Day 4 | Day 6 >>

Day 5

📔 Giorno 5

Arrays

A differenza delle variabili, un array può memorizzare molti valori. Ogni valore in un array ha un indice e ogni indice ha un riferimento in un indirizzo di memoria. È possibile accedere a ciascun valore utilizzando i loro indici. L'indice di un array parte da zero e l'indice dell'ultimo elemento è diminuito di uno rispetto alla lunghezza dell'array.

Un array è una raccolta di diversi tipi di dati ordinati e modificabili. Un array consente di memorizzare elementi duplicati e tipi di dati diversi. Una array può essere vuoto o può contenere valori di tipi di dati diversi.

Come creare un array vuoto

In JavaScript, possiamo creare un array in diversi modi. Vediamo i diversi modi per creare un array. È molto comune usare const invece di let per dichiarare una variabile di un array. Se si usa const, significa che non si usa più il nome di quella variabile.

  • Usare il costruttore Array
// syntax
const arr = Array()
// or
// let arr = new Array()
console.log(arr) // []
  • Usare le parentesi quadre ([])
// syntax
// This the most recommended way to create an empty list
const arr = []
console.log(arr)

Come creare un array contenente valori

Array con valori iniziali. Utilizziamo la proprietà length per trovare la lunghezza di un array.

const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of strings, fruits
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of strings, vegetables
const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] // array of strings, products
const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] // array of web technologies
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] // array of strings, countries

// Print the array and its length

console.log('Numbers:', numbers)
console.log('Number of numbers:', numbers.length)

console.log('Fruits:', fruits)
console.log('Number of fruits:', fruits.length)

console.log('Vegetables:', vegetables)
console.log('Number of vegetables:', vegetables.length)

console.log('Animal products:', animalProducts)
console.log('Number of animal products:', animalProducts.length)

console.log('Web technologies:', webTechs)
console.log('Number of web technologies:', webTechs.length)

console.log('Countries:', countries)
console.log('Number of countries:', countries.length)
Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
Number of numbers: 6
Fruits: ['banana', 'orange', 'mango', 'lemon']
Number of fruits: 4
Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Number of vegetables: 5
Animal products: ['milk', 'meat', 'butter', 'yoghurt']
Number of animal products: 4
Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
Number of web technologies: 7
Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
Number of countries: 5
  • Un array può contenere elementi di diversi tipi di dati
const arr = [
    'Asabeneh',
    250,
    true,
    { country: 'Finland', city: 'Helsinki' },
    { skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] }
] // arr containing different data types
console.log(arr)

Creare un array usando la funzione split

Come abbiamo visto nella sezione precedente, possiamo dividere una stringa in diverse posizioni e convertirla in un array. Vediamo gli esempi seguenti.

let js = 'JavaScript'
const charsInJavaScript = js.split('')

console.log(charsInJavaScript) // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]

let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'
const companies = companiesString.split(',')

console.log(companies) // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"]
let txt =
  'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
const words = txt.split(' ')

console.log(words)
// the text has special characters think how you can just get only the words
// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"]

Accedere agli elementi dell'array usando l'indice

Si accede a ciascun elemento di un array utilizzando il suo indice. L'indice di un array parte da 0. L'immagine seguente mostra chiaramente l'indice di ciascun elemento dell'array.

arr index

const fruits = ['banana', 'orange', 'mango', 'lemon']
let firstFruit = fruits[0] // we are accessing the first item using its index

console.log(firstFruit) // banana

secondFruit = fruits[1]
console.log(secondFruit) // orange

let lastFruit = fruits[3]
console.log(lastFruit) // lemon
// Last index can be calculated as follows

let lastIndex = fruits.length - 1
lastFruit = fruits[lastIndex]

console.log(lastFruit)  // lemon
const numbers = [0, 3.14, 9.81, 37, 98.6, 100]  // set of numbers

console.log(numbers.length)  // => to know the size of the array, which is 6
console.log(numbers)         // -> [0, 3.14, 9.81, 37, 98.6, 100]
console.log(numbers[0])      //  -> 0
console.log(numbers[5])      //  -> 100

let lastIndex = numbers.length - 1;
console.log(numbers[lastIndex]) // -> 100
const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
] // List of web technologies

console.log(webTechs)        // all the array items
console.log(webTechs.length) // => to know the size of the array, which is 7
console.log(webTechs[0])     //  -> HTML
console.log(webTechs[6])     //  -> MongoDB

let lastIndex = webTechs.length - 1
console.log(webTechs[lastIndex]) // -> MongoDB
const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
] // List of countries

console.log(countries)      // -> all countries in array
console.log(countries[0])   //  -> Albania
console.log(countries[10])  //  -> Kenya

let lastIndex = countries.length - 1;
console.log(countries[lastIndex]) //  -> Kenya
const shoppingCart = [
  'Milk',
  'Mango',
  'Tomato',
  'Potato',
  'Avocado',
  'Meat',
  'Eggs',
  'Sugar'
] // List of food products

console.log(shoppingCart) // -> all shoppingCart in array
console.log(shoppingCart[0]) //  -> Milk
console.log(shoppingCart[7]) //  -> Sugar

let lastIndex = shoppingCart.length - 1;
console.log(shoppingCart[lastIndex]) //  -> Sugar

Modificare gli elementi dell'array

Un array è mutabile (modificabile). Una volta creato un array, è possibile modificarne il contenuto degli elementi.

const numbers = [1, 2, 3, 4, 5]
numbers[0] = 10      // changing 1 at index 0 to 10
numbers[1] = 20      // changing  2 at index 1 to 20

console.log(numbers) // [10, 20, 3, 4, 5]

const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]

countries[0] = 'Afghanistan'  // Replacing Albania by Afghanistan
let lastIndex = countries.length - 1
countries[lastIndex] = 'Korea' // Replacing Kenya by Korea

console.log(countries)
["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"]

Methods to manipulate array

Esistono diversi metodi per manipolare un array. Questi sono alcuni dei metodi disponibili per gestire gli array:Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift

Il Costruttore dell'array

Array: Crea un array.

const arr = Array() // creates an an empty array
console.log(arr)

const eightEmptyValues = Array(8) // it creates eight empty values
console.log(eightEmptyValues) // [empty x 8]

Creare valori statici con fill

fill: Riempe l'array con l'elemento specificato.

const arr = Array() // creates an an empty array
console.log(arr)

const eightXvalues = Array(8).fill('X') // it creates eight element values filled with 'X'
console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X']

const eight0values = Array(8).fill(0) // it creates eight element values filled with '0'
console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0]

const four4values = Array(4).fill(4) // it creates 4 element values filled with '4'
console.log(four4values) // [4, 4, 4, 4]

Concatenare array usando concat

concat: Concatena due array.

const firstList = [1, 2, 3]
const secondList = [4, 5, 6]
const thirdList = firstList.concat(secondList)

console.log(thirdList) // [1, 2, 3, 4, 5, 6]
const fruits = ['banana', 'orange', 'mango', 'lemon']                 // array of fruits
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables
const fruitsAndVegetables = fruits.concat(vegetables)                 // concatenate the two arrays

console.log(fruitsAndVegetables)
["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"]

Ottenere la lunghezza dell'array

Length:Per conoscere la lunghezza dell'array.

const numbers = [1, 2, 3, 4, 5]
console.log(numbers.length) // -> 5 is the size of the array

Ottenere l'indice di un elemento nell'array

indexOf:Per verificare se un elemento esiste in un array. Se esiste, viene restituito l'indice, altrimenti viene restituito -1.

const numbers = [1, 2, 3, 4, 5]

console.log(numbers.indexOf(5)) // -> 4
console.log(numbers.indexOf(0)) // -> -1
console.log(numbers.indexOf(1)) // -> 0
console.log(numbers.indexOf(6)) // -> -1

Controlla che l'elemento esista nell'array.

  • Controlla gli elementi in una lista.
// let us check if a banana exist in the array

const fruits = ['banana', 'orange', 'mango', 'lemon']
let index = fruits.indexOf('banana')  // 0

if(index === -1){
   console.log('This fruit does not exist in the array')  
} else {
    console.log('This fruit does exist in the array')
}
// This fruit does exist in the array

// we can use also ternary here
index === -1 ? console.log('This fruit does not exist in the array'): console.log('This fruit does exist in the array')

// let us check if an avocado exist in the array
let indexOfAvocado = fruits.indexOf('avocado')  // -1, if the element not found index is -1
if(indexOfAvocado === -1){
   console.log('This fruit does not exist in the array')  
} else {
    console.log('This fruit does exist in the array')
}
// This fruit does not exist in the array

Ottenere l'ultimo indice di un elemento nell'array

lastIndexOf: Fornisce la posizione dell'ultimo elemento dell'array. Se esiste, restituisce l'indice, altrimenti restituisce -1.

const numbers = [1, 2, 3, 4, 5, 3, 1, 2]

console.log(numbers.lastIndexOf(2)) // 7
console.log(numbers.lastIndexOf(0)) // -1
console.log(numbers.lastIndexOf(1)) //  6
console.log(numbers.lastIndexOf(4)) //  3
console.log(numbers.lastIndexOf(6)) // -1

includes:Per verificare se un elemento esiste in un array. Se esiste, restituisce true, altrimenti restituisce false.

const numbers = [1, 2, 3, 4, 5]

console.log(numbers.includes(5)) // true
console.log(numbers.includes(0)) // false
console.log(numbers.includes(1)) // true
console.log(numbers.includes(6)) // false

const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
] // List of web technologies

console.log(webTechs.includes('Node'))  // true
console.log(webTechs.includes('C'))     // false

Verificare l'array

Array.isArray:Per verificare se il tipo di dato è un array.

const numbers = [1, 2, 3, 4, 5]
console.log(Array.isArray(numbers)) // true

const number = 100
console.log(Array.isArray(number)) // false

Convertire l'array in stringa

toString:Converts array to string

const numbers = [1, 2, 3, 4, 5]
console.log(numbers.toString()) // 1,2,3,4,5

const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook

Unire elementi array

join: Viene utilizzato per unire gli elementi dell'array; l'argomento passato nel metodo join verrà unito con l'array e restituito come stringa. Per impostazione predefinita, unisce con una virgola, ma possiamo passare diversi parametri stringa che possono unire gli elementi.

const numbers = [1, 2, 3, 4, 5]
console.log(numbers.join()) // 1,2,3,4,5

const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']

console.log(names.join()) // Asabeneh,Mathias,Elias,Brook
console.log(names.join('')) //AsabenehMathiasEliasBrook
console.log(names.join(' ')) //Asabeneh Mathias Elias Brook
console.log(names.join(', ')) //Asabeneh, Mathias, Elias, Brook
console.log(names.join(' # ')) //Asabeneh # Mathias # Elias # Brook

const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
] // List of web technologies

console.log(webTechs.join())       // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB"
console.log(webTechs.join(' # '))  // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB"

Dividere gli elementi dell'array

Slice: Per ritagliare più elementi in un intervallo. Richiede due parametri: posizione iniziale e posizione finale. Non include la posizione finale.

  const numbers = [1,2,3,4,5]

  console.log(numbers.slice()) // -> it copies all  item
  console.log(numbers.slice(0)) // -> it copies all  item
  console.log(numbers.slice(0, numbers.length)) // it copies all  item
  console.log(numbers.slice(1,4)) // -> [2,3,4] // it doesn't include the ending position

Il metodo Splice con gli array

Splice: Richiede tre parametri: posizione iniziale, numero di volte da rimuovere e numero di elementi da aggiungere.

  const numbers = [1, 2, 3, 4, 5]
  numbers.splice()
  console.log(numbers)                // -> remove all items
  const numbers = [1, 2, 3, 4, 5]
	numbers.splice(0,1)
  console.log(numbers)            // remove the first item
  const numbers = [1, 2, 3, 4, 5, 6]
	numbers.splice(3, 3, 7, 8, 9)
  console.log(numbers.splice(3, 3, 7, 8, 9))  // -> [1, 2, 3, 7, 8, 9] //it removes three item and replace three items

Aggiungere un elemento all'array usando push

Push: Per aggiungere un elemento alla fine di un array esistente, si usa il metodo push.

// syntax
const arr  = ['item1', 'item2','item3']
arr.push('new item')
console.log(arr)
// ['item1', 'item2','item3','new item']
const numbers = [1, 2, 3, 4, 5]
numbers.push(6)
console.log(numbers) // -> [1,2,3,4,5,6]

numbers.pop() // -> remove one item from the end
console.log(numbers) // -> [1,2,3,4,5]
let fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.push('apple')
console.log(fruits)    // ['banana', 'orange', 'mango', 'lemon', 'apple']

fruits.push('lime')
console.log(fruits)   // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']

Rimuovere l'ultimo elemento usando pop

pop: Rimuove l' elemento in coda.

const numbers = [1, 2, 3, 4, 5]
numbers.pop() // -> remove one item from the end
console.log(numbers) // -> [1,2,3,4]

Rimuovere un elemento dall'inizio dell'array

shift: Rimuove l'elemento in testa (prima posizione).

const numbers = [1, 2, 3, 4, 5]
numbers.shift() // -> remove one item from the beginning
console.log(numbers) // -> [2,3,4,5]

Aggiungere un elemento in prima posizione dell'array

unshift: Aggiunge un elemento in prima posizione.

const numbers = [1, 2, 3, 4, 5]
numbers.unshift(0) // -> add one item from the beginning
console.log(numbers) // -> [0,1,2,3,4,5]

Invertire l'ordine dell'array

reverse: Inverti l'ordine degli elementi.

const numbers = [1, 2, 3, 4, 5]
numbers.reverse() // -> reverse array order
console.log(numbers) // [5, 4, 3, 2, 1]

numbers.reverse()
console.log(numbers) // [1, 2, 3, 4, 5]

Ordinare gli elementi di un array

sort: dispone gli elementi dell'array in ordine crescente. L'ordinamento richiede una funzione di richiamo; vedremo come utilizzare l'ordinamento con una funzione di richiamo nelle prossime sezioni.

const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
]

webTechs.sort()
console.log(webTechs) // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"]

webTechs.reverse() // after sorting we can reverse it
console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"]

Array di array

Gli array possono memorizzare diversi tipi di dati, compreso l'array stesso. Creiamo un array di array

const firstNums = [1, 2, 3]
const secondNums = [1, 4, 9]

const arrayOfArray =  [[1, 2, 3], [1, 2, 3]]
console.log(arrayOfArray[0]) // [1, 2, 3]

 const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
 const backEnd = ['Node','Express', 'MongoDB']
 const fullStack = [frontEnd, backEnd]
 console.log(fullStack)   // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]]
 console.log(fullStack.length)  // 2
 console.log(fullStack[0])  // ["HTML", "CSS", "JS", "React", "Redux"]
 console.log(fullStack[1]) // ["Node", "Express", "MongoDB"]

🌕 Sei diligenti e hai già ottenuto molti risultati. Hai appena completato le sfide del 5° giorno e sei a 5 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.

💻 Esercizio

Esercizio: Livello 1

const countries = [
  'Albania',
  'Bolivia',
  'Canada',
  'Denmark',
  'Ethiopia',
  'Finland',
  'Germany',
  'Hungary',
  'Ireland',
  'Japan',
  'Kenya'
]

const webTechs = [
  'HTML',
  'CSS',
  'JavaScript',
  'React',
  'Redux',
  'Node',
  'MongoDB'
]
  1. Dichiarare un array vuoto;
  2. Dichiarare un array con un numero di elementi superiore a 5
  3. Trovare la lunghezza dell'array
  4. Ottenere il primo elemento, l'elemento centrale e l'ultimo elemento dell'array.
  5. Dichiarare un array chiamato mixedDataTypes, inserire diversi tipi di dati nell'array e trovare la lunghezza dell'array. La dimensione dell'array deve essere maggiore di 5
  6. Dichiarare una variabile array chiamata itAziende e assegnare i valori iniziali Facebook, Google, Microsoft, Apple, IBM, Oracle e Amazon.
  7. Stampare l'array utilizzando console.log().
  8. Stampare il numero di aziende nell'array
  9. Stampare la prima azienda, la metà e l'ultima azienda
  10. Stampare ogni azienda
  11. Cambiare il nome di ogni azienda in maiuscolo, uno per uno, e stamparli.
  12. Stampare la matrice come una frase: Facebook, Google, Microsoft, Apple, IBM, Oracle e Amazon sono grandi aziende IT.
  13. Controllare se una certa azienda esiste nell'array itCompanies. Se esiste, restituisce l'azienda, altrimenti restituisce un'azienda non trovata.
  14. Filtrare le aziende che hanno più di una "o" senza il metodo del filtro.
  15. Ordinare l'array usando il metodo sort().
  16. Invertire l'array utilizzando il metodo reverse().
  17. Estrarre le prime 3 società dall'array.
  18. Eliminare le ultime 3 aziende dall'array.
  19. Eliminare dall'array l'azienda o le aziende IT centrali.
  20. Rimuovere la prima azienda IT dall'array
  21. Rimuovere l'azienda o le aziende IT centrali dall'array.
  22. Rimuovere l'ultima azienda IT dall'array
  23. Rimuovere tutte le aziende IT

Esercizio: Livello 2

  1. Creare un file separato countries.js e memorizzare l'array dei Paesi in questo file, creare un file separato web_techs.js e memorizzare l'array webTechs in questo file. Accedere a entrambi i file nel file main.js

  2. Per prima cosa rimuovete tutte le punteggiature, cambiate la stringa in array e contate il numero di parole nell'array.

    let text =
    'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
    console.log(words)
    console.log(words.length)
    ["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"]
    
    13
  3. Nel seguente carrello della spesa aggiungere, rimuovere, modificare gli articoli

    const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey']
    • aggiungere "Carne" all'inizio del carrello se non è già stato aggiunto
    • aggiungere "Zucchero" alla fine del carrello se non è già stato aggiunto
    • rimuovere "Miele" se si è allergici al miele
    • modificare il tè in "Tè verde".
  4. Nell'array dei Paesi controllare se 'Etiopia' esiste nell'array, se esiste stampare 'ETIOPIA'. Se non esiste, aggiungerlo all'elenco dei paesi.

  5. Nell'array webTechs verificare se Sass esiste nell'array e se esiste stampare 'Sass è un preprocesso CSS'. Se non esiste, aggiungere Sass all'array e stampare l'array.

  6. Concatenare le due variabili seguenti e memorizzarle in una variabile fullStack.

    const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
    const backEnd = ['Node','Express', 'MongoDB']
    
    console.log(fullStack)
    ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]

Esercizio: Livello 3

  1. Di seguito è riportata una serie di 10 studenti di età:

    const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
    • Ordinare l'array e trovare l'età minima e massima
    • Trovare l'età mediana (un elemento centrale o due elementi centrali divisi per due)
    • Trovare l'età media (tutti gli elementi divisi per il numero di elementi)
    • Trovare l'intervallo delle età (max meno min)
    • Confrontare il valore di (min - media) e (max - media), utilizzando il metodo abs(). 1.Tagliare i primi dieci Paesi dalla countries array
  2. Trovare il/i Paese/i centrale/i nella countries array

  3. Dividere l'array di paesi in due array uguali se è pari. Se l'array dei paesi non è pari, un altro paese per la prima metà.

🎉 CONGRATULAZIONI ! 🎉

<< Day 4 | Day 6 >>