简体   繁体   中英

Array.filter is not working properly

I have an array and i want to remove a record from it i have use Array.filter() but its return same array as it is.

My Code:

var url = window.location.pathname,
    orderId = url.split('/').slice(-2)[0];
var Cart = JSON.parse(localStorage.getItem('Cart'));
newCart=Cart.filter(function(item) {
    if (parseInt(item.orderId) == parseInt(orderId)) {
        return {};
    }
    else
    {
        return item;
    }
});
localStorage.setItem('Cart',JSON.stringify(newCart));

You should return true or false in the filter in order to filter data from an array.
Return true to add the element in the filtered list, false otherwise.
So you can do something like this using filter()

newCart = Cart.filter(function(item) {
    return parseInt(item.orderId, 10) != parseInt(orderId, 10);
});

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