Home > Back-end >  Sorting and filtering Multi Dimensional array from API in angular
Sorting and filtering Multi Dimensional array from API in angular

Time:03-07

Here is my API data

{
id: 1, name: "pro package", 
subscriptionList: [ {id: 1, amount: 999}, {id: 2, amount: 2999}, {id: 3, amount: 1999} ]
},
{
id: 2, name: "basic package", 
subscriptionList: [ {id: 1, amount: 299} ]
}

Desired Result is

Basic Package - 299
Pro Package - Starting from 999 - 2999

This is how im sorting right now

this._services.subscriptionapi().subscribe((result) => {
this.packages = result.sort(
  (a, b) =>
   b.subscriptionList[0].amount -
   a.subscriptionList[0].amount
);
});

How can i sort amount inside subscriptionList by showing only the Min and Max values (eg: 299 - 2999)

CodePudding user response:

I think the best way is to combine filter and sort functions like this :

this._services.subscriptionapi().subscribe((result) => {
this.packages = result.filter(
(a) => 
a.subscriptionList[0].amount > 2999
&& &.subscriptionList[0].amount < 299
)
.sort(
  (a, b) =>
   b.subscriptionList[0].amount -
   a.subscriptionList[0].amount
);
});

Hope I understood your question well.

CodePudding user response:

you needn't sort the list. You can simple loop over result and over subscriptionList

this.packages=this.result.map((x)=>{
  const obj={min:x.subscriptionList[0].amount,
             max:x.subscriptionList[0].amount,
             name:x.name}
  x.subscriptionList.forEach((y) => {
    obj.min = obj.min > y.amount ? y.amount : obj.min;
    obj.max = obj.max < y.amount ? y.amount : obj.max;
  });
  return obj
})
  • Related