I am getting an array from a database (in descending order) and I print them on the front in a table and in a graph as shown in the image:
but in the part of the graph I want to order it in ascending order and I do the following:
export class PruebasComponent implements OnInit {
data: any[];
dataSource: PeriodicElement[] = [];
lineChartData: ChartDataSets[];
.......
ngOnInit() {
this.loading = true;
this.datos.getDesktopLimit().subscribe(
res => {
this.loading = false;
this.data = [res];
this.dataSource = this.data[0]; //aqui almaceno el arreglo y lo paso al componente html
this.barChartData = true;
this.getFilter(this.dataSource); // ejecuto la funcion getFilter()
}
)
}
with a sort I order it in ascending order to pass it to the graph
getFilter(data) {
console.log(data);
data.sort((a, b) => a.id - b.id); //ordenar de forma ascendente para la grafica
for (let entry of data) {
this.date.push(moment(entry.created).format('DD-MM-YYYY HH:mm'))
this.time.push(entry.total_load_time * 0.001)
}
this.lineChartData = [{ data: this.time, label: 'Time Render' }];
this.lineChartLabels = this.date;
this.loading = false
}
Indeed it sorts me but the table is also sorted ascending
You are having a reference problem, in javascript (TS too), all objects pass by reference. You have to separate the two objects: table and graph.
Then:
Now when you do a sort, the others will not be changed automatically, the idea is that when you pass it to string and then to JSON again, you lose the reference.
doing it with JSON.parse is safest, it depends on how deep your objects are (objects within objects).
Other ways to make copies of objects and avoid referencing are with
Object.assign()
the and spread operator....
The latter consume less resources since the JSON.parse method requires a little more CPU, you will notice this if you are going to be converting large arrays (>30k records).
I hope it helps you, greetings!