0

I've a parent array which has some objects in it and those objects have a property called created_at now I want to sort the parent array by the date.

let parent_array = [ { id: 1, date: '2022-12-01T20:34:52.000000Z' }, { id: 2, date: '2022-12-06T20:34:52.000000Z', }, ];

Now I want to sort parent_array by date value.

I tried this method

parent_array.filter((node: any) => {
            return node.sort((a: any, b: any) => {
                return new Date(b.created_at) - new Date(a.created_at);
            });
        })

But I'm getting an error "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)"

Thank You Sakib

  • Typescript is complaining because Date is an object but you are trying to subtract them, convert them to numbers explicitly. `new Date(b.created_at).valueOf() - new Date(a.created_at).valueOf()`. But the `filter()` doesn't make any sense, and the return will always be true, so no filtering will happen – pilchard Dec 01 '22 at 21:20
  • Typescript duplicate: [The left -hand and right hand side of an arithmetic operation must be of type 'any', 'number' or an enum type](https://stackoverflow.com/questions/48274028/the-left-hand-and-right-hand-side-of-an-arithmetic-operation-must-be-of-type-a). (Always research the error you're getting first before posting a new question) – pilchard Dec 01 '22 at 21:24
  • thanks everyone the issue was i weren't using the new Date().getTime() when i did use it. it started working. Reference: https://stackoverflow.com/questions/31118182/javascript-sort-by-date-multidimensional-json-array – Sakib Hasan Dec 01 '22 at 21:26
  • I'm still confused. You are using `filter` which is sending a single object into a `sort`. - ahh, I just saw that you changed that in your answer below – Kinglish Dec 01 '22 at 21:28
  • Yeah. But now I removed the filter and it's working fine – Sakib Hasan Dec 01 '22 at 21:29
  • If you're going to use Typescript take the time to make use of its typings. Always using `any` isn't helping you. – pilchard Dec 01 '22 at 21:41

1 Answers1

0
let parent_array = [ { id: 1, date: '2022-12-01T20:34:52.000000Z' }, { id: 2, date: '2022-12-06T20:34:52.000000Z', }, ];

const tcx = (a: any, b: any) => {
        return new Date(b.date).getTime() - new Date(a.date).getTime();
};

console.log(parent_array.sort(tcx));
pilchard
  • 12,414
  • 5
  • 11
  • 23