简体   繁体   中英

Remove items in array with quantity 0 in React Native

I want to remove the items in array that has quantity of zero. i tried:

    constructor(props) {
    super(props);
    this.state = {
    serviceAvailed: [{"label": "Top", "quantity": 2}, {"label": "Bottoms", "quantity": 0}, 
    {"label": "Jacket", "quantity": 1}, {"label": "Beddings", "quantity": 0}, {"label": "Shoes", 
    "quantity": 0}];,
    }

On component did mount i looped the items inside the array and called the method removeItem that is supposed to remove all the items that has zero quantity

   componentDidMount() {
    let {serviceAvailed  } = this.state;
    serviceAvailed = this.state.array.map((item, i) => {
    let quantity=parseInt(item.quantity);
       if(quantity<1){
       this.removeItem(i)
       }});
   }

Function to remove the array

   removeItem(index) {
    const serviceAvailed = this.state.serviceAvailed;
    serviceAvailed.splice(index, 1);
    this.setState({ serviceAvailed });
    console.log(serviceAvailed)
   }

expected result: serviceAvailed: [{"label": "Top", "quantity": 2}, {"label": "Jacket", "quantity": 1}];,

You can use array filter method

let newArr = serviceAvailed.filter(function (e) {
        return e.quantity > 0;
    });
    console.log(newArr );

The problem

array::map is meant to map every element from an array to a new array. The operation is a one-to-one correspondence . It's also meant to be a pure function, which means it has ZERO side effects, like removing elements of the array it is currently iterating over. array::reduce and array::filter are better options for removing elements, or otherwise "reducing" the input.

Solution

Using array::filter allows you to iterate over over an array and return a new array containing only elements that pass the filter predicate. Create a filter predicate function that returns true or false if an object's quantity property is greater than 0 .

const quantityGreaterThanZero = ({ quantity }) => quantity > 0;

Note: 0 is a "falsey" value, numbers greater than 0 are "truthy" values, so the above can be simplified to simply return the quantity. If it is truthy the predicate function is true, else it is false.

const quantityGreaterThanZero = ({ quantity }) => quantity;

Now you can pass your predicate function as the callback to array::filter .

const greaterThanZero = data.filter(quantityGreaterThanZero);

 const data = [ { label: "Top", quantity: 2 }, { label: "Bottoms", quantity: 0 }, { label: "Jacket", quantity: 1 }, { label: "Beddings", quantity: 0 }, { label: "Shoes", quantity: 0 } ]; const quantityGreaterThanZero = ({ quantity }) => quantity; console.log(data.filter(quantityGreaterThanZero));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM