I have an array called arrayReceived
containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount
value in a new array called arraySorted
. These objects are sorted based on their amount
parameter. There may be multiple objects with the same lowest amount value. I need to extract all objects with the lowest amount
value and place them in arrayLowest
. The remaining objects should be stored in arrayHigher
. How can I accomplish this using typescript?
this.arrayRevceived.sort(function (a,b)) {
return a.amount - b.amount;
}
this.arraySorted = arrayReceived.splice(0,6);
}
// it is working till here, the problem starts here
for(let i =0; i < this.arraySorted.length; i ++) {
if (this.arraySorted[0].amount === this.arraySorted[i].amount){
this.arrayLowest.push(this.arraySorted[i]);
} else {
this.arrayHighest.push(this.arraySorted[i]);
}
}
In my attempt to achieve this, I am using a for loop to compare with index [0] because the array is already sorted, so the lowest value will be at index [0]. If the values match with subsequent objects, they are added to arrayLowest
, otherwise to arrayHighest
. However, this approach is not yielding the expected results. Any suggestions would be appreciated. Thank you.