skip to Main Content

I have original data like this in array arr

[
{Id:1,
Date:20/06/2023,
ProdId:1
},
{Id:2,
Date:21/06/2023,
ProdId:1
},
{Id:3,
Date:21/06/2023,
ProdId:2
},
{Id:4,
Date:23/06/2023,
ProdId:2
},
{Id:5,
Date:20/06/2023,
ProdId:3
}
]

I want the items with unique prodIds and it should be latest. I should get the below data

[
{Id:2,
Date:21/06/2023,
ProdId:1
},
{Id:4,
Date:23/06/2023,
ProdId:2
},
{Id:5,
Date:20/06/2023,
ProdId:3
}
]

What I need to do? Thanks in advance!!

2

Answers


  1. I’m sure there is probably an easier way, but this worked for me:

        this.customers.sort((a, b) =>
          new Date(b.Date) > new Date(a.Date) ? 1 : -1
        );
        var uniqueCustomers = this.customers.filter((value, index, array) =>
          array.findIndex((c) => c.ProdId === value.ProdId) === index
        );
        console.log(JSON.stringify(uniqueCustomers));
    

    This code first sorts by the date. Then filters for unique values based on the ProdId.

    Login or Signup to reply.
  2. const myArray = [
      {Id:1,
      Date:20/06/2023,
      ProdId:1
      },
      {Id:2,
      Date:21/06/2023,
      ProdId:1
      },
      {Id:3,
      Date:21/06/2023,
      ProdId:2
      },
      {Id:4,
      Date:23/06/2023,
      ProdId:2
      },
      {Id:5,
      Date:20/06/2023,
      ProdId:3
      }
    ];
    

    Trick:

    const modifiedArray = myArray.filter((item, idx, array) =>
              array.findLastIndex((c) => c.ProdId === item.ProdId) === idx
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search