Exercise 13: Function to Filter a List of Products on Sale
Learn to use functions to filter product lists. Ideal for beginners who want to build functionalities like "sales" or "searches."
The main objective is to learn how to work with functions that return objects and how to use arrow functions to filter data in an array.
Activity
-
Create an array of objects called
productoswhere each object represents a product with the propertiesnombreandenOferta(This last one must be a Boolean value.) -
Create an arrow function called
filtrarEnOfertathat takes the arrangementproductosas an argument. -
Inside the function, use the method
filterto return a new arrangement containing only the products that are on sale (enOfertaIt must betrue4. Call the function and store the result in a variable calledproductosEnOferta. -
Sample
productosEnOfertaon the console.
Solution
Step 1: Create the index.html file
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Función que Filtra una Lista de Productos en Oferta</title>
</head>
<body>
<h1>Ejercicio 13: Función que Filtra una Lista de Productos en Oferta</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
// Crear el arreglo de productos
const productos = [
{ nombre: "Laptop", enOferta: true },
{ nombre: "Celular", enOferta: false },
{ nombre: "Tablet", enOferta: true },
{ nombre: "Monitor", enOferta: false },
];
// Definir la función flecha para filtrar productos en oferta utilizando el método filter de JavaScript
const filtrarEnOferta = (productos) =>
productos.filter((producto) => producto.enOferta);
// Llamar a la función y guardar el resultado en una variable
let productosEnOferta = filtrarEnOferta(productos);
// Mostrar los productos en oferta
console.log("Productos en oferta:", productosEnOferta);
🔎Review the following sections where you will find more information on this topic: