Skip to main content

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

  1. Create an array of objects calledproductoswhere each object represents a product with the propertiesnombre and enOferta(This last one must be a Boolean value.)

  2. Create an arrow function calledfiltrarEnOfertathat takes the arrangementproductosas an argument.

  3. Inside the function, use the methodfilterto 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.

  4. SampleproductosEnOfertaon the console.

Solution

Step 1: Create the index.html file

HTML
<!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

JavaScript
// 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);
info

🔎Review the following sections where you will find more information on this topic: