Is there a way to filter an array of objects based on their year without altering the original object? Whenever I apply a filter, it affects both the newly created object and the original one. However, I need the original object to remain unchanged so that I can apply different filters.
I've experimented with methods like .assign, JSON.parse(JSON.stringify(Object)), and the clone deep function but haven't found a solution yet.
This is the component code:
export class LeaderboardComponent implements OnInit {
title = "Leaderboard";
public navList = [];
public navFilterList = [];
routeCount = 0;
logsCount = 0;
completeJourneys = 0;
selectFilter = "";
selectDateFilter = "";
currentDate = new Date;
minutes = 1000 * 60;
hours = this.minutes * 60;
days = this.hours * 24;
month = this.days * 30;
years = this.days * 365;
currTimestamp = this.currentDate.getTime();
clonedObject;
objCopy = [];
constructor(private leaderboardService: LeaderboardService) { }
ngOnInit() {
this.leaderboardService.getNavList()
.subscribe(data => {
this.navList = data;
this.objCopy = Object.assign([], data);
console.log("here");
console.log(this.objCopy);
});
}
orderByDate(){
console.log(this.objCopy);
var tempLogArray = 0;
this.navFilterList = this.objCopy;
if(this.selectDateFilter != "all"){
for(var i = 0; i < this.navFilterList.length; i ++){
for(var j = 0; j < this.navFilterList[i].user.routes.length; j ++){
for(var k = 0; k < this.navFilterList[i].user.routes[j].logs.length; k++){
var logDate = new Date(this.navFilterList[i].user.routes[j].logs[k].attemptDate);
this.navFilterList[i].user.routes[j].logs[k].timestamp = logDate.getTime();
}
this.navFilterList[i].user.routes[j].logs = this.navFilterList[i].user.routes[j].logs.filter(log => ((this.currTimestamp - log.timestamp)/this.years) < 1);
}
}
console.log("here year");
}
}
}
The HTML code calling the filter by date function:
<select [(ngModel)]="selectDateFilter" (change)="orderByDate()" class="form-group" style="width: 100px;" >
<option disabled selected value="" >Order by: </option>
<option value = "week">Last 7 Days</option>
<option value = "month">Last Month</option>
<option value = "year" >Last Year</option>
<option value = "all" >All Time</option>
</select>
I expect objCopy to always retain the data fetched from the JSON file via API, but instead, it gets updated with the filtered data.