Heathcliff
Heathcliff

Reputation: 119

JavaScript - Pushing Objects into Array failed

I saw this question being asked a lot but i have not been able to solve it yet, so here goes! I'm working on a project where i display a list of orders. I want to be able to filter the orders by date. Therefore i'm trying to push each filtered order into a new array, but this gives me the following error:

"TypeError: filteredOrders.push is not a function"

I've tried to tweak my push syntax as i thought i had it wrong but to no avail. Each order is returned as an Object. How can i push these objects into an Array? The orders array i am looping through is also a array of objects. Here's my code for a more clear example:

data: function () {
    return {
        isFilterShown: false,
        IsOrderDetailShown: false,
        selectedDateFrom: new Date(),
        selectedDateTill: new Date(),
    }
},

methods: {
    applyFilter: function () {
        let dateFrom = this.selectedDateFrom;
        let dateTill = this.selectedDateTill;
        let filteredOrders = Array;

        this.orders.forEach(function (order) {
            if (order.createdAt >= moment(dateFrom).format('DD-MM-Y') && order.createdAt <= moment(dateTill).format('DD-MM-Y')) {
                console.log(order.createdAt, order);
                return order;
            }
            filteredOrders.push(order);
        })
        // this.orders = this.filteredOrders;
        this.isFilterShown = false;
    },

Screenshot of console: enter image description here

Upvotes: 0

Views: 618

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16447

Array is a function, not an empty array. This line

let filteredOrders = Array;

doesn't create an empty array. It assigns the function Array to filteredOrders. You probably want

let filteredOrders = [];

Upvotes: 2

kunal panchal
kunal panchal

Reputation: 798

The Assignment here:

let filteredOrders = Array;

is type of just a function and no constructor function is generated. instead you can try doing this

let filteredOrders = new Array(); 
or 
let filteredOrders = [];

which will give you access to the Array methods

Upvotes: 1

Related Questions