Salta el contingut

Solucions dels Exercicis UT04 - Estructures definides per l'usuari en JavaScript

Exercici 86: Array de números - Suma total

const numeros = [10, 20, 15, 30, 25];

function calcularSuma(array) { let suma = 0; for (let i = 0; i < array.length; i++) { suma += array[i]; } return suma; }

console.log(calcularSuma(numeros)); // 100

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 86" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 87: Buscar element duplicat

const array1 = [1, 2, 3, 4, 3, 5]; const array2 = [1, 2, 3, 4, 5];

function teDuplicats(array) {

for (let j = i + 1; j < array.length; j++) { if (array[i] === array[j]) { return true; } } } return false; }

console.log(teDuplicats(array1)); // true console.log(teDuplicats(array2)); // false

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 87" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

const original = [1, 2, 3, 4, 5];

function invertirArray(array) { const invertit = []; for (let i = array.length - 1; i >= 0; i--) { invertit.push(array[i]); } return invertit; }

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 88" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 89: Filtrar números pars

const numeros = [1, 2, 3, 4, 5, 6, 7, 8];

function filtrarPars(array) {

for (let i = 0; i < array.length; i++) { if (array[i] % 2 === 0) { pars.push(array[i]); } } return pars; }

console.log(filtrarPars(numeros)); // [2, 4, 6, 8]

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 89" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

const animals = ["gat", "gos", "gat", "ocell", "gat"];

function contarOcurrencies(array, element) { let contador = 0; for (let i = 0; i < array.length; i++) { if (array[i] === element) { contador++; } } return contador; }

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 90" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 91: Trobar el número més gran

const numeros = [15, 42, 8, 99, 23, 67];

function trobarMesGran(array) { let major = array[0]; for (let i = 1; i < array.length; i++) { if (array[i] > major) {

} } return major; }

console.log(trobarMesGran(numeros)); // 99

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 91" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 92: Eliminar element d'un array (PENDENT DE CODI)

// TODO: Afegir codi original de l'exercici (eliminació d'un element d'un array)
// Exemple provisional:
const nombres = [1,2,3,4,5];
function eliminarElement(array, valor) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] === valor) {
            array.splice(i,1);
            return true;
        }
    }
    return false;
}
eliminarElement(nombres,3);

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 92" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 93: Cercar element en un array (PENDENT DE CODI)

// TODO: Afegir codi original de l'exercici (cerca d'un element en un array) // Exemple provisional:

function cercar(array, terme) { for (let i = 0; i < array.length; i++) { if (array[i] === terme) return i; // retorna posició } return -1; } console.log(cercar(alumnes,"Pere")); // 2 console.log(cercar(alumnes,"Laura")); // -1

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 93" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 94: Dividir array en chunks

const numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const mida = 3;

const chunks = []; for (let i = 0; i < array.length; i += mida) { chunks.push(array.slice(i, i + mida)); } return chunks; }

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 94" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 95: Crear un objecte estudiants

const estudiant = {

nota: 7.5, assignatura: "JavaScript", haAprovat: function() { return this.nota >= 5; } };

console.log(estudiant.nom); // "Maria" console.log(estudiant.haAprovat()); // true

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 95" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 96: Array de contactes

const contactes = [ { nom: "Joan", telefon: "123456789" }, { nom: "Maria", telefon: "987654321" }, { nom: "Pere", telefon: "555555555" } ];

function cercarContacte(array, nom) { for (let i = 0; i < array.length; i++) { if (array[i].nom === nom) { return array[i]; } } return null; }

console.log(cercarContacte(contactes, "Maria")); // { nom: "Maria", telefon: "987654321" } console.log(cercarContacte(contactes, "Luis")); // null

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 96" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 97: Calcular mitjana de notes

const estudiants = [

{ nom: "Anna", nota: 6 }, { nom: "Pere", nota: 9 } ];

function calcularMitjana(array) { let suma = 0; for (let i = 0; i < array.length; i++) { suma += array[i].nota; } return suma / array.length; }

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 97" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 98: Ordenar array de números

const numeros = [45, 12, 89, 23, 56, 34];

function ordenarAscendent(array) { const copiat = [...array]; for (let i = 0; i < copiat.length; i++) { for (let j = i + 1; j < copiat.length; j++) { if (copiat[i] > copiat[j]) { let temp = copiat[i]; copiat[i] = copiat[j]; copiat[j] = temp; } } } return copiat; }

console.log(ordenarAscendent(numeros)); // [12, 23, 34, 45, 56, 89]

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 98" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 99: Crear taula de multiplicar

function taulaMultiplicar(numero) { const resultat = []; for (let i = 1; i <= 10; i++) { resultat.push(numero * i); } return resultat; }

console.log(taulaMultiplicar(5)); // [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 99" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 100: Filtrar per propietat d'objecte

const productes = [ { nom: "Laptop", preu: 800, disponible: true }, { nom: "Ratolí", preu: 25, disponible: false }, { nom: "Teclat", preu: 60, disponible: true }, { nom: "Monitor", preu: 250, disponible: true } ];

function filtrarDisponibles(array) { const disponibles = []; for (let i = 0; i < array.length; i++) { if (array[i].disponible) { disponibles.push(array[i]); } } return disponibles; }

console.log(filtrarDisponibles(productes)); // Retorna només els productes amb disponible: true

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 100" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 101: Concatenar strings d'un array

const tecnologies = ["JavaScript", "HTML", "CSS", "React"];

function concatenarStrings(array) { let resultat = ""; for (let i = 0; i < array.length; i++) { if (i < array.length - 1) { resultat += array[i] + ", "; } else { resultat += array[i]; } } return resultat; }

console.log(concatenarStrings(tecnologies)); // "JavaScript, HTML, CSS, React"

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 101" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 102: Crear objecte calculadora amb historial

const calculadora = { historial: [],

sumar: function(a, b) { const resultat = a + b; this.historial.push(${a} + ${b} = ${resultat}); return resultat; },

restar: function(a, b) { const resultat = a - b; this.historial.push(${a} - ${b} = ${resultat}); return resultat; },

multiplicar: function(a, b) { const resultat = a * b; this.historial.push(${a} × ${b} = ${resultat}); return resultat; },

mostrarHistorial: function() { return this.historial; } };

calculadora.sumar(10, 5); calculadora.restar(20, 3); calculadora.multiplicar(4, 6); console.log(calculadora.mostrarHistorial());

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 102" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 103: Validar format email

function validarEmail(email) { const posicioArroba = email.indexOf('@'); const posicioPunt = email.indexOf('.');

return posicioArroba !== -1 && posicioPunt !== -1 && posicioPunt > posicioArroba; }

console.log(validarEmail("usuario@ejemplo.com")); // true console.log(validarEmail("usuarioexemple.com")); // false console.log(validarEmail("usuario@ejemplocom")); // false

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 103" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>

Exercici 104: Trobar números primers

function esNumeroPrimer(numero) { if (numero <= 1) return false; for (let i = 2; i < numero; i++) { if (numero % i === 0) return false; } return true; }

function filtrarPrimers(array) { const primers = []; for (let i = 0; i < array.length; i++) { if (esNumeroPrimer(array[i])) { primers.push(array[i]); } } return primers; }

const numeros = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; console.log(filtrarPrimers(numeros)); // [2, 3, 5, 7, 11]

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 104" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>


Exercici 105: Crear agenda de cites

const agenda = { cites: [],

afegirCita: function(data, hora, descripcio) { this.cites.push({ data: data, hora: hora, descripcio: descripcio }); },

eliminarCita: function(data) { for (let i = 0; i < this.cites.length; i++) { if (this.cites[i].data === data) { this.cites.splice(i, 1); return true; } } return false; },

cercarCita: function(data) { for (let i = 0; i < this.cites.length; i++) { if (this.cites[i].data === data) { return this.cites[i]; } } return null; },

llistarCites: function() { return this.cites; } };

agenda.afegirCita("2025-11-15", "10:00", "Reunió amb client"); agenda.afegirCita("2025-11-16", "14:30", "Visita mèdica"); agenda.afegirCita("2025-11-17", "09:00", "Entrega projecte"); console.log(agenda.llistarCites());

<iframe height="300" style="width: 100%;" scrolling="no" title="UT04 - Exercici 105" src="" frameborder="no" loading="lazy" allowtransparency="true"> </iframe>