¡Te damos la bienvenida a este reto!

1

¡Bienvenido al mundo de JavaScript!

Día 1

2

Variables, funciones y sintaxis básica

3

Tipos de datos

4

Playground - Retorna el tipo

5

Tipos de datos - pt 2

Día 2

6

Operadores

7

Hoisting y coerción

8

Playground - Calcula la propina

9

Alcance de las variables

Día 3

10

Condicionales

11

Playground - Calcula años bisiestos

12

Switch

13

Playground - Obten información de mascotas según su tipo

14

Ciclos

15

Playground - Dibuja un triangulo

Día 4

16

Arrays

17

Playground - Encuentra al michi mas famoso

18

Objetos

19

Playground - Obten el promedio de los estudiantes

Día 5 - Checkpoint

20

Playground - encuentra el palindromo más grande

Día 6

21

Reasignación y redeclaración

22

Modo estricto

Día 7

23

Debugging y manejo de errores

24

Programación funcional

Quiz: Día 7

Día 8

25

Closures

26

Playground - Crea una calculadora con closures

27

Higher order functions

28

Playground - Crea tu propio método map

Día 9

29

ECMAScript

30

TC39

Quiz: Día 9

Día 10 - Checkpoint

31

ES6

32

ES7

33

Playground - Task planner

Día 11

34

Asincronismo

35

Playground - Promesas

36

Manejando el asincronismo

37

Playground - Resuelve el callback hell usando promesas

38

Playground - Resuelve el callback hell usando async/await

Día 12

39

Arrays a profundidad

40

Métodos de arrays: Every, Find y findIndex

41

Playground - Válida el formulario

Día 13

42

Métodos de arrays: Includes, Join y concat

43

Playground - agrupa los productos

44

Métodos de arrays: Flat y FlatMap

45

Playground - Encuentra la ubicación del valor buscado

Día 14

46

Mutable functions

47

Playground - Modifica una lista de compras

48

Métodos de arrays: sort

49

Playground - Ordena los productos

Día 15 - Checkpoint

50

Playground - Sistema de reservaciones de un hotel

Día 16

51

Programación orientada a objetos en JavaScript

52

Objetos literales

53

Playground - Congela el objeto recursivamente

Día 17

54

Prototipos en JavaScript

55

Playground - Modifica el prototype de los arrays

56

Playground - Crea un auto usando clases

Día 18

57

Abstracción en JavaScript

58

Playground - Sistema de carrito de compras

59

Encapsulamiento en JavaScript

60

Playground - Encapsula datos de los usuarios

Día 19

61

Herencia en JavaScript

62

Playground - Jerarquía de animales

63

Polimorfismo en JavaScript

64

Playground - Sistema de pagos

Día 20 - Checkpoint

65

Playground - Agenda de vuelos

Live Class

66

30 días de JS con Juan DC

67

30 días de JS con Nicobytes

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Aprende todo un fin de semana sin pagar una suscripción 🔥

Aprende todo un fin de semana sin pagar una suscripción 🔥

Regístrate

Comienza en:

3D
22H
31M
19S

Playground - agrupa los productos

43/67

Aportes 49

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.

🛡️Escudo anti-spoilers🛡️

Mi solucion:

export function groupProducts(products, category) {
  const res = {}

  //Productos que cumple con la categoria
  const category_products = products.filter(x => x.category == category)

  res['products'] = category_products.map(x => x.name).join(", ")
  res['totalPrice'] = category_products.reduce(((acum, { price }) => acum + price), 0)


  return res
}

🛡️Escudo anti-spoilers🛡️

tal vez está poco entendible pero ahi esta, si alguien tiene duda se lo puedo explicar

export function groupProducts(products, category) {
  // Tu código aquí
  return {
    products:
      products.filter(obj => obj.category === category)
              .map(obj => obj.name).join(", "),
    totalPrice:
      products.filter(obj => obj.category === category)
              .map(obj => obj.price)
              .reduce((acc, cur) => acc + cur, 0),
  };
}

Cuando se le pilla el punto, esto de jugar con las funciones es muy potente
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
  const prodCategoria = products.filter((item) => item.category == category);
  const names = prodCategoria.flatMap((item)=>item.name).join(", ");
  const totalPrice = prodCategoria.reduce((total, item) => total + item.price,0);
  return { products:names,totalPrice };
}

Buenas, comparto mi solucion, la verdad me siento muy orgulloso ya que lo realice sin necesidad de ninguna ayuda, me costo dure como tres horas pero al final lo logre, al final no me habia dado cuenta y le habia puesto una ‘s’ mas en el objeto de retorno al totalPrice jajajajaja, le comparto mi codigo:


Mi aporte

export function groupProducts(products, category) {
  // Tu código aquí
  let prods = "";
  let price = 0;
  products.forEach(el => {
    if (el.category === category) {
      prods = prods + el.name + ", ";
    price = price + el.price
    }
  });

  let result = {
    products: prods.trimEnd().slice(0, prods.length - 2),
    totalPrice: price
  }

  return result

}


















export function groupProducts(products, category) {
  let data = products.filter((element) => element.category === category);
  const totalPrice = data.reduce((suma, number) => suma.price + number.price);
  const productsName = data.reduce((array, elem) => {
    array.push(elem.name)
    return array
  },[]) 
  
  return { products: productsName.join(', '), totalPrice}
  
}

💢 💢 💢 ANTI SPOILER 💢 💢 💢

Mi respuesta.

export function groupProducts(products, category) {
  // Tu código aquí
  const groupProducts = {
    products: [],
    totalPrice: 0
  };
  products.forEach(product => {
    if (product.category == category) {
      groupProducts.products.push(product.name);
      groupProducts.totalPrice += product.price;
    }
  });

  groupProducts.products = groupProducts.products.join(", ");
  return groupProducts;
}

Solucion1. Metodos filter, map y reduce.

export function groupProducts(products, category) {
  const filtered = products.filter(product => product.category === category);
  return {
    products: filtered.map(product => product.name).join(", "),
    totalPrice: filtered.reduce((acc, val) => acc.price + val.price)
  }
}

Solucion 2. Metodo reduce + metodo concat:

    export function groupProducts(products, category) {
  return products.reduce((acc, val) => {
    if (acc.products === undefined) {
      acc.products = '';
      acc.totalPrice = 0;
    }
    if (val.category === category) {
      if (acc.products !== '') {
        acc.products = acc.products.concat(', ' + val.name);
      } else {
        acc.products = val.name;
      }
      acc.totalPrice += val.price;
    }
    return acc;
  }, {})
}
export function groupProducts(products, category) {
  // Tu código aquí
  let subTotal = 0;
  const items = [];
  const productByCategoria = products.filter((product) => {
    if (product.category === category) {
      items.push(product.name);
      subTotal += product.price;
      return true;
    }
  });
  return { products: items.join(', '), totalPrice: subTotal };
}

Comparto mi solución
.
.
.
.
.
.
.

export function groupProducts(products, category) {
  // Tu código aquí
  const filtered = products.filter((p) => p.category === category)
  const totalPrice = filtered.reduce((a, p) => a + p.price, 0);
  const productsString = filtered.map(p => p.name).join(", ");
  return {
    products: productsString,
    totalPrice
  }

}

Linda la propuesta de devolver los productos como un string… 😃

export function groupProducts(productos, category) {
  // Tu código aquí

  const productsfilters = productos.filter(
    product => product.category === category)
    .reduce((acc, curr) => {

      if (acc.products.length === 0) {
        return {
          products: acc.products.concat(curr.name),
          totalPrice: acc.totalPrice + curr.price
        }
      } else {

        return {
          products: acc.products.concat(", ").concat(curr.name),
          totalPrice: acc.totalPrice + curr.price
        }

      }

    }, {
      products: "",
      totalPrice: 0,
    });


  return productsfilters;
};

mi solución:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
    // Tu código aquí
    const groupedProducts = {};
  
    const filteredProducts = products.filter(product => product.category === category);

    groupedProducts.products = filteredProducts.map(product => product.name).join(", ");
    groupedProducts.totalPrice = filteredProducts.map(product => product.price).reduce((acumulador, numero) => acumulador + numero);
  
    return groupedProducts;
}

Ez

export function groupProducts(products, category) {
  let output = {
    products: [],
    totalPrice: 0
  }

  products.map((item) => { 
    if (item.category == category) {
      output.totalPrice += item.price
      output.products.push(item.name)
    }
  })

  output.products = output.products.join(", ")
  return output;
}

Mi solucion:

export function groupProducts(products, category) {
  const arrayproductos = [];
  let total = 0;
  for (let i = 0; products.length > i; i++) { 
    const producto = products[i].name;


    if (category === products[i].category) { 
      arrayproductos.push(products[i].name);
      total = total + products[i].price;
    }
  }
  let nombreproducto = arrayproductos.join(", ")

  let result = {
    products: nombreproducto,
    totalPrice: total
  }

  return result;
}

Mi versión de la solución, con lo aprendido:

  let descripProducts = "";
  let totalPrice = 0;

  products.filter((value) => {
    if (value.category === category) {
      if (descripProducts === "") {
        descripProducts = value.name;
      } else {
        descripProducts = `${descripProducts}, ${value.name}`;
      }
      totalPrice = totalPrice + value.price;
      return value;
    }
  });

  return (products = {
    products: descripProducts,
    totalPrice: totalPrice,
  }); 

MI SOLUCION 💪
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
  const producstByCategoty = products.filter(product => product.category === category);
  const nameProducts = producstByCategoty.map(product => product.name).join(", ");
  const totalPrice = producstByCategoty.reduce((total, product) => total + product.price, 0);
  return {
    products: nameProducts,
    totalPrice
  };
}

Esta es mi solución, cuidado con los spoilers:
.
.
.
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
  let totalPrice = 0;
  let pNameArray = [];

  let selectedProducts = products.filter(item => item.category === category);

  selectedProducts.forEach(item => {
    totalPrice += item.price;
    pNameArray.push(item.name);
  });

  let auxPName = pNameArray.join(", ");
  return { "products": auxPName, "totalPrice": totalPrice };
}

Mi solución:

export function groupProducts(products, category) {
  let output = {
    products: "",
    totalPrice: 0
  }
  const filteredProducts = products.filter((product) => product.category === category)

  output.products = filteredProducts.map(({ name }) => name).join(", ")

  filteredProducts.forEach((product) => output.totalPrice += product.price)

  return output
}

estaba facil

export function groupProducts(products, category) {
  const filteredByCategory = products.filter(item => item.category == category)
  const names = filteredByCategory.map(item => item.name).join(', ')
  const suma = filteredByCategory.reduce((a, b) => a + b.price, 0)

  return { products: names, totalPrice: suma }
} 

˗ˏˋ ★ ˎˊ˗

export function groupProducts(products, category) {

  let checkCategory = products.some(p => p.category === category)

  let result = {
    products: '',
    totalPrice: 0
  }


  if (checkCategory) {

    let filterByCategory = []

    for (let p of products) {

      p.category === category ? filterByCategory.push(p.name) : null
      p.category === category ? result.totalPrice += p.price : null

    }

    result.products += filterByCategory.join(', ')

  }

  return result

}

++
+
+
+
+
++
+
+

export function groupProducts(products, category) {
  let productsFilter = products.filter((product) => {
    return product.category === category;
  })
  let productos = {
    products: "",
    totalPrice: 0
  }
  let nameProducts = [];
  for (const [key, value] of Object.entries(productsFilter)) {
    nameProducts.push(value.name);
    productos.totalPrice += value.price;
  }
  productos.products = nameProducts.join(", ");
  return productos;
}

Aquí mi solución usando un for in:

export function groupProducts(products, category) {
  let totalPrice = 0;
  var prod = [];
  const result = products.filter(prod => prod.category === category);
  for (const prop in result) {
    prod.push(result[prop].name);
    totalPrice += result[prop].price;
  }
  return { products: prod.join(", "), totalPrice };
}

🛡️Escudo anti-spoilers🛡️

export function groupProducts(products, category) {
  return {
    products: products.filter(item => item.category === category).map(item => item.name).join(', '),
    totalPrice: products.filter(item => item.category === category).reduce((a, c) => a + c.price, 0)
  };
}


Solu
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

function groupProducts(products, category) {

const selectedProducts = products.filter(product => product.category === category);
let selectedNames = [];
let sumatoryOfPrices = 0;

for(let i=0; i<selectedProducts.length; i++){
selectedNames.push(selectedProducts[i].name);
sumatoryOfPrices = sumatoryOfPrices + selectedProducts[i].price;
};

return {
products: selectedNames.join(", "),
totalPrice: sumatoryOfPrices
}
}

Aquí mi solución:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

<export function groupProducts(products, category) {
  //filtro los productos segun la cateoria en productsCategory
  let productsCategory = products.filter(item => item.category == category);
  //sumo el precio de los productos filtrados
  let sumtotal = productsCategory.reduce((sum, item) => sum + item.price, 0);
  //obtengo el name de los productos filtrados en productoName
  let productsName = productsCategory.map((item) => item.name).join(', ');
  return { products: productsName, totalPrice: sumtotal };
}> 

the sol guys:

export function groupProducts(products, category) {
  const filteredproducts = products.filter(item => item.category === category);
  let result = {products: "", totalPrice: 0};
  for (const product of filteredproducts) {
    if (result.products == "") {
      result.products = result.products.concat('', product.name);
    } else {
      result.products = result.products.concat(', ', product.name);
    }
    result.totalPrice += product.price;
  }
  return result;
}

Hola, aqui mi solución. Use el metodo filter y un simple bucle for of
.
.
.
.
.
.
.

function groupProducts(products, category) {
  const filteredProducts = products.filter((product) => product.category == category)
  const names = []
  let totalPrice = 0
  for (let product of filteredProducts) {
    names.push(product.name)
    totalPrice += product.price
  }
  return { products: names.join(", "), totalPrice }
}

Hola! aquí mi solución 😀
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.

export function groupProducts(products, category) {
  // Tu código aquí
  const filteredProducts = products.filter((product) => product.category === category)
  return {
    products: filteredProducts.map((product) => product.name).join(', '),
    totalPrice: filteredProducts.reduce((acum, product) => acum + product.price, 0)
  }

}
export function groupProducts(products, category) {
  // Tu código aquí
  const filteredProducts = products.filter(product => product.category === category)

  const mappedProducts = filteredProducts.map(product => product.name)

  const totalPrice = filteredProducts.reduce((acc, curr) => acc + curr.price, 0) 

  return {
      products: mappedProducts.join(", "),
      totalPrice
  }
}

.
.
.
.
.
.
.
.
.
Mi solución solo con reduce

export const groupProducts = (products,category,) =>
  products.reduce(
    (obj, product) => {
      if (product.category === category) {
        obj["totalPrice"] = obj["totalPrice"] + product.price;
        obj["products"] = (!obj["products"])
          ? product.name
          : obj["products"].concat(`, ${product.name}`);
      }
      return obj;
    },
    { products: "", totalPrice: 0 },
  );

SPOILLLLLLLLEER
.
.
.
.
.
.
.
.
.

  const productsByCategory = products.filter(
    (product) => product.category === category
  );

  const productsName = productsByCategory
    .map((product) => product.name)
    .join(', ');

  const totalPrice = productsByCategory.reduce(
    (acum, product) => acum + product.price,
    0
  );

  return {
    products: productsName,
    totalPrice,
  };

Mi solución
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
  const productsByCategory = [];
  let totalPrice = 0;

  products
    .filter((product) => {
      return product.category === category;
    })
    .map((product) => {
      productsByCategory.push(product.name);
      totalPrice += product.price;
    });

  return {
    products: productsByCategory.join(", "),
    totalPrice: parseInt(totalPrice),
  };
}

Solución… 😄
.
Un reto bastante divertido, primero filtramos los productos por su categoría mediante la función filter().
.
Luego, creamos un array con únicamente los nombres de los productos filtrados, utilizando map() y la función join(", ") que nos devolverá una cadena con los productos separados por ", ".
.
Finalmente, acumulamos el precio de los productos filtrados en una variable mediante reduce(), y retornamos un objeto con las propiedades correspondientes.
.

export function groupProducts(products, category) {
  // Filtramos por categoría
  let filtered = products.filter((product) => product.category === category);

  // Creamos un array con los nombres de los fittrados
  let productNames = filtered.map((product) => product.name).join(", ");

  // Accumulamos el precio total de los filtrados
  let price = filtered.reduce((acc, product) => {
    return acc + product.price;
  }, 0);

  // Retornamos el objeto
  return {
    products: productNames,
    totalPrice: price
  };

}

Mi Solución
*
*
*
*
*
*
*

export function groupProducts(products, category) {
 
  const filteredProducts = products.filter(prod => prod.category === category)

  const productNames = filteredProducts.map(prod => prod.name).join(', ')

  const totalPrice = filteredProducts.reduce((acc,cur) => acc + cur.price, 0)

  return {
    products: productNames,
    totalPrice
  }
}

¡Hola, Desafío cumplido 😃!
Mi solución,
Se detalla hasta abajo.⬇








export function groupProducts(products, category) {
  const even = (element) => element.category === category;
  const filterByCategory = products.some(even);

  let rta = { products: "", totalPrice: 0 };
 

  if (filterByCategory) {
    const myList = products.filter(even);
    const myNames = myList.map(item => item.name);
    rta.products = myNames.join(", ");
    rta.totalPrice= myList.reduce(
      (accumulator, currentValue) => accumulator + currentValue.price, 0
    );

  }
  return rta;
}

Aquí dejo mi solución usando los métodos de los contenidos. Espero les ayude:

export function groupProducts(products, category) {
  // Tu código aquí
  let reply = {
    products: "",
    totalPrice: 0,
  }

  let categories = products.map(element => element.category)
  if (categories.includes(category)) {
    let matchedProducts = products.filter(product => product.category == category)
    let matchedProductsNameList = []
    matchedProducts.forEach(product => {
      reply.totalPrice += product.price
      matchedProductsNameList.push(product.name)
    });
    reply.products = matchedProductsNameList.join(", ")
  }

  return reply
}

Mi solución
.
.
.
.
.
.

export function groupProducts(products, category) {
  let total_products = { products: '', totalPrice: 0 };
  let product_list_name = [];
  let products_find = products.filter(product => {
    return product.category == category;
  });
  products_find.forEach(product => {
    product_list_name.push(product.name);
    total_products.totalPrice += product.price;
  })
  total_products.products = product_list_name.join(', ');
  return total_products;
}

.
.
.
.
.
.
.

export function groupProducts(products, category) {
  // Tu código aquí
  let nameProduct = [];
  let totalPrice = 0;
  products.forEach(product => {
    if (product.category === category) {
      nameProduct.push(product.name);
      totalPrice += product.price
    }
  });

  return {products: nameProduct.join(', '), totalPrice: totalPrice}
}

.
.

.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.

Mi solucion :3

export function groupProducts(products, category) {
  let outProducts = products.reduce((acc, curr) => {
    if (curr.category == category) {
      acc.products.push(curr.name)
      acc.totalPrice += curr.price
    }
    return acc
  }, { products: [], totalPrice: 0 })

  outProducts.products = outProducts.products.join(', ')
  return outProducts
}

Solución n.n

.
.
.
.
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
    let totalPrice = 0
    let productsFilter = products.filter(product => {
    if (product.category === category) {
            totalPrice += product.price
            return true
        }
        return false
    }).map(product => product.name)
    
    return {
        products: productsFilter.join(', '),
        totalPrice
    }
}

MI solución:

Curiosa la pequeña trampilla del espacio jajaja,o bueno, para mi fue curiosa:

export function groupProducts(products, category) {
  const categoria = products.filter((a) => a.category == category);
  const producto = categoria.map((a) => a.name);
  const total = categoria.reduce((a, b) => a.price + b.price);
  return {
    products: producto.join(", "),
    totalPrice: Number(total),
  };
}

Hola, dejo mi solucion
Caminito anti spoilers
🚗
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Llegamos 📍

const productsCategory = products.filter((product) => product.category === category)
    const productsName = productsCategory.map((product) => product.name)
    const productsSum = productsCategory.reduce((acumulador, numero) => (acumulador + numero.price), 0);
    return {
        products: productsName.join(', '), 
        totalPrice: productsSum
    }

Solución

export function groupProducts(products, category) {
  // Tu código aquí
  let productsByCategory = [];
  let totalPrice = 0;
  products.forEach(product => {
    if (product.category === category) {
      productsByCategory.push(product.name);
      totalPrice += product.price;
    }
  });
  return {
    products: productsByCategory.join(", "),
    totalPrice: totalPrice
  }
}

Adjunto mi solución:
.
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {
  const productsPerCategory = []
  let totalPrice = 0
  products.forEach(product => {
    if (product.category.includes(category)) {
      productsPerCategory.push(product.name)
      totalPrice += product.price
    }
  })
  return {
    products: productsPerCategory.join(', '),
    totalPrice
  }
}
export function groupProducts(products, category) {

  let sortProducts = [];
  let total = 0;

  for (let product of products) {

    if (product.category === category) {
      sortProducts.push(product.name);
      total += product.price;
      }
    
  }

  return {
    products: sortProducts.join(", "),
    totalPrice: total,
  }

 
}

Mi aporte:
.
.
.
.
.
.
.
.
.
.
.

function groupProducts(products, category) {

    let myProducts = [];
    let prices = [];

    products.forEach(element => {
        if(element.category === category){
            myProducts.push(element.name);
            prices.push(element.price);
        }        
    });
    let total = prices.reduce((sum, num) => sum + num, 0);

return {"products": myProducts.join(", "), totalPrice: total}
 
};

Alerta Spoiler
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {

  const categoryFilter = products.filter(prod => prod.category === category);

  const products = categoryFilter.reduce((a, b) => `${a.name}, `.concat(b.name));

  const totalPrice = categoryFilter.reduce((a, b) => a.price + b.price);

  return ({
    products,
    totalPrice
  })
}

Aporto mi solución
.
.
.
.
.
.
.
.
.
.
.
.

export function groupProducts(products, category) {

  //Creo un arreglo de productos y declaro e inicializo sumaPrecios en 0
  let cadenaProductos = []
  let sumaPrecios = 0

  //Compruebo todos los productos que coincidan con la categoría que recibí como parámetro y los que coinciden los agrego a cadenaProductos que por el momento es un array y agrego su precio a sumaPrecios
  products.forEach(producto => {
    if (producto['category'] === category) {
      cadenaProductos.push(producto['name'])
      sumaPrecios+=producto['price']
    }
  })

  //Una vez que filtré todos los productos los convierto en un string con el método join
  cadenaProductos = cadenaProductos.join(', ')
  
  return {
    products: cadenaProductos,
    totalPrice: sumaPrecios
  }
}

Spoiler:
.
.
.
.
.
.
.
.
.
.

function groupProducts(products, category) {
    const names = products
    .filter(prod => prod.category === category)
    .reduce((a, b) => `${a.name}, ${b.name}`);

    const prices = products
    .filter(prod => prod.category === category)
    .reduce((a, b) => a.price + b.price);

    return{
        products: names, 
        totalPrice: prices
    };
};
undefined