Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
React.js, Array.filter not filtering out items that doesn't meet the condition

I'm working on a shopping cart in React, and to be able to delete single items, I want to compare the id of the item with the id of all the items in the array, so that if the id are the same, I can filter out that item from the array. However the filter method doesn't seem to work. Am I missing something?

Function:

const deleteItem = () => {
    cartArray.map((e) => {
      console.log("I'm working");
      if (e.id != id) {
        setCartArray(cartArray.filter((e) => e.id !== id));
      }
    });
  };

Component where function is called:

const CartProduct = ({
  cartArray,
  setCartArray,
  imgUrl,
  nameUrl,
  priceUrl,
  id,
}) => {
  const shortenProductName = (name) => {
    if (name.length > 40) return name.slice(0, 40) + "...";
    else return name;
  };

  const deleteItem = () => {
    cartArray.map((e) => {
      console.log("I'm working");
      if (e.id != id) {
        setCartArray(cartArray.filter((e) => e.id !== id));
      }
    });
  };
  

  return (
    <div className="cart-product">
      <p></p>
      <img src={imgUrl} alt="product image" />
      <div className="name-price-container">
        <p>{shortenProductName(nameUrl)}</p>
        {/* <p>{nameUrl.slice(0, ) + "..."}</p> */}
        <h4>€ {priceUrl}</h4>
      </div>
      <DeleteIcon onClick={deleteItem} />
    </div>
  );
};

Thank you!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You should probably remove the whole .map part. Also, pass the id into the function.

const deleteItem = id => {
   setCartArray(cartArray.filter(e => e.id !== id));
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

The filter() method creates a new array with all elements that pass the test implemented so you can just filter the cartArray with the filter function solely.

const deleteItem = () => {
   setCartArray(cartArray.filter(e => e.id !== id));
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

You dont need the map and I would probably simplify the whole thing. Here a working example: https://codesandbox.io/s/wizardly-wilson-fxwje?file=/src/App.js

import React from "react";

export default function App() {
  const [cartArray, setCartArray] = React.useState([
    { id: 1, title: "first" },
    { id: 2, title: "second" },
    { id: 3, title: "third" }
  ]);

  const deleteItem = (e) => {
    setCartArray(
      cartArray.filter(
        (cartItem) => parseInt(e.target.value, 10) !== cartItem.id
      )
    );
  };

  return (
    <div className="App">
      <div>
        {cartArray.map((item) => {
          return (
            <button onClick={deleteItem} value={item.id}>
              {item.title}
            </button>
          );
        })}
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda