I want to store all the input data of the textbox to an array with unique index number each so I can control them. The problem is that it only assigns zero index for all of them.
todoField.addEventListener('keypress', function (b) {
if (b.key === 'Enter' && todoField.value != 0) {
let newtodo = todoField.value
task = [newtodo]
}
}
declear a function outside the addEventListener and push the new items to the function that will give them a unique id and store them too.
this is how you should do it.
tasks = []; // array decleartion
todoField.addEventListener('keypress', function (b) {
if (b.key === 'Enter' && todoField.value != 0) {
let newtodo = todoField.value
tasks.push(newtodo);
} }
Now tasks array will contain all your tasks.
thank you.
Related
I have a list in angular, an array. OnInit it gets filled from the right corresponding database items. I created a form above it. When you enter something in the form, it acts like a filter. This works, the first time. When you erase something from the form and enter something else, the list should be refreshed and afterwards filtered based on the new input. This doesn't happen. I put the formula that happens on onInit in my function to refill the list.
Below you can find my function (I left the console logs in) and a screenshot of the problem. First I look for a user (joeri.boons#hi10.be) which returns three results. Than I erase the user and look based on a month 7. The screen returns a new unfilterd list while in the console it still holds the list of 3 x user joeri.boons#hi10.be. So there is an inconsistency to. If you look at screen result you would think of a filter problem, the console points at a refreshproblem.
if more code is required let me know.
updateWithFilter(): void {
console.log("function update filter reached")
console.log(this.listadapted);
if(this.listadapted == true){
// this.timesheetsHandled = {} as TimeSheet[];
this.getHandledSheet();
console.log("getHandledSheet executed")
}
if(this.filterUsername.trim() && !this.filterYear && !this.filterMonth){
console.log("option 1 reached")
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
this.timesheetsHandled = this.timesheetsHandled.filter(sheet => sheet.username == this.filterUsername);
this.listadapted = true;
} else if(!this.filterUsername.trim() && !this.filterYear && this.filterMonth){
console.log("option 2 reached");
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
console.log("before filter");
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
this.timesheetsHandled = this.timesheetsHandled.filter(sheet => sheet.month == this.filterMonth);
console.log("after filter");
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
// console.log(this.timesheetsHandled.filter(sheet => sheet.month == this.filterMonth));
this.listadapted = true;
} else if .. more options
}
ngOnInit(): void {
this.getHandledSheet();
}
getHandledSheet(): void {
this.timesheetService.getAllTimesheets().subscribe({next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => sheet.status == 'HANDLED') }}) ;
}
My guess would be that this is caused by loading data in ngOnInit. As the documentation (https://angular.io/api/core/OnInit) states : [...] It is invoked only once when the directive is instantiated.
I suspect that you create one instance and re-use it and the ngOnInit method does not get called again.
UPDATE:
The issue is that the call to this.getHandledSheet(); does a call to .. .subscribe({next: .. which is delayed and the rest of the function is executed first.
So the actual code after next: is only executed after the timeSheetService is done loading the data.
So either you apply the filter in the
{next: (response: TimeSheet[]) => {this.timesheetsHandled = response.filter(sheet => sheet.status == 'HANDLED') }}
block after filtering for 'HANDLED' or you'll try to await in the update function.
Create two variables, one that will always remain unfiltered, then another that will be filtered.
The problem will be that the original list is filtered, hence you are losing the original data after filtering!
timesheetHandled: TimeSheet[];
timesheetHandledOriginal: TimeSheet[];
updateWithFilter(): void {
console.log('function update filter reached');
console.log(this.listadapted);
if (this.listadapted == true) {
// this.timesheetsHandled = {} as TimeSheet[];
this.getHandledSheet();
console.log('getHandledSheet executed');
}
if (this.filterUsername.trim() && !this.filterYear && !this.filterMonth) {
console.log('option 1 reached');
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
this.timesheetsHandled = this.timesheetHandledOriginal.filter(
sheet => sheet.username == this.filterUsername
);
this.listadapted = true;
} else if (!this.filterUsername.trim() && !this.filterYear && this.filterMonth) {
console.log('option 2 reached');
console.log(this.filterUsername.trim());
console.log(this.filterYear);
console.log(this.filterMonth);
console.log('before filter');
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
this.timesheetsHandled = this.timesheetHandledOriginal.filter(
sheet => sheet.month == this.filterMonth
);
console.log('after filter');
this.timesheetsHandled.forEach(sheet => console.log(sheet.username));
// console.log(this.timesheetsHandled.filter(sheet => sheet.month == this.filterMonth));
this.listadapted = true;
}
// else if .. more options
}
ngOnInit(): void {
this.getHandledSheet();
}
getHandledSheet(): void {
this.timesheetService.getAllTimesheets().subscribe({
next: (response: TimeSheet[]) => {
this.timesheetsHandled = response.filter(sheet => sheet.status == 'HANDLED');
this.timesheetHandledOriginal = JSON.parse(JSON.stringify(this.timesheetsHandled));
},
});
}
So , I wanna make a discord bot which calculates our study time and adda the study time
And makes a leaderboard out of it and some more things , but my problem here is that I want it to store seperate data for each member
For example :
If I type login it should start a stopwatch and when I type logout it should store the time I studied and same goes for the other members
Please help me with this , I gotta make it as soon as possible
Thank you
With the limited information you provided I assume something like this could be viable:
let userStartTimes = [];
//...
if(command == "login") {
// only add element if it doesnt exist already
if(!userStartTimes.some(el => el.id == message.author.id)) {
userStartTimes.add({id: message.author.id, time: Date.now()});
}
}
if(command == "logout") {
let index = userStarTimes.findIndex(el => el.id == message.author.id);
// check if user has logged in before
if(index != -1) {
let msecSpent = Date.now() - userStartTimes[index].time;
// add to leaderboard
}
}
I have data from an movie-api I want to sort based on a select menu, either by year in descending order or title in alphabetical order.
Although Im only updating state in the sort function, not using the variable any where, the data thats already mapped out, and in a different array, updates accordingly. I guess its somehow related to the first change in state for each of the two differen variables?
Any idea how I should solve this correctly and why this is happening?
const sortData = (e) => {
if (e === "year"){
const yearData = data.sort(function(a, b) {
const yearA = a.Year;
const yearB = b.Year;
if (yearA < yearB) {
return -1;
}
if (yearA > yearB) {
return 1;
}
return 0;
});
setYearData(yearData);
}
if (e === "title") {
const titleData = data.sort(function(a, b) {
const titleA = a.Title.toUpperCase();
const titleB = b.Title.toUpperCase();
if (titleA < titleB) {
return -1;
}
if (titleA > titleB) {
return 1;
}
return 0;
});
setTitleData(titleData);
}
}
The sort() method sorts the elements of an array in place, so the data(state) changed without using setState (It may cause some unpredictability happened in the execution)
You can use the sort() method on a copy of the array, so it doesn't affect your state array, I guess this change may work:
use [...data].sort(...) instead of data.sort(...)
Array.sort(), in your case data.sort() updates the original array in addition to returning it. Seems like your data variable is some sort of global that gets changed during sort().
Within each element in an array, there may or may not be a value that I need to grab. If the value is not in one element, I want to go to the next element to look for it. I'd like to know how to write the statement to do that in my Postman test. I already know how to get the values when they exist, but I want to go through each element until I find what I'm looking for to put in the variable.
I've googled how to write the code, but I'm new to this and I'm having trouble.
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("Date", jsonData.array[0].field[1]);
if (postman.setGlobalVariable("Date", jsonData.array[0].field[1]) === ???
else (postman.setGlobalVariable("Date", jsonData.array[1].field[1]);)
Hi, Here is a sample response (thanks!): You can see the first element does not have the value, "NeedTheseDates" that I need to grab, but the second element does.
"SampleArray": [
{
"Date": "2019-05-18T00:00:00.0000000-04:00",
"NeedTheseDates": [],
"Anything": "data",
"OnlyDate": "2019-06-03T00:00:00.0000000-04:00"
},
{
"Date": "2019-06-16T00:00:00.0000000-04:00",
"NeedTheseDates": [
"2019-07-02T00:00:00.0000000-04:00",
"2019-07-03T00:00:00.0000000-04:00",
"2019-07-04T00:00:00.0000000-04:00",
"2019-07-05T00:00:00.0000000-04:00",
"2019-07-06T00:00:00.0000000-04:00",
"2019-07-07T00:00:00.0000000-04:00",
"2019-07-08T00:00:00.0000000-04:00",
"2019-07-09T00:00:00.0000000-04:00",
"2019-07-10T00:00:00.0000000-04:00",
"2019-07-11T00:00:00.0000000-04:00",
"2019-07-12T00:00:00.0000000-04:00"
],
Not very sure about the problem statement. So trying all combinations
If there are only two cases where the value could be (index 0 or 1)
let someDate = jsonData.array[0].field[1] === '???' ?
jsonData.array[0].field[1] : jsonData.array[1].field[1];
postman.setGlobalVariable('Date', someDate);
If the length of array is dynamic but the date you are looking for in field is always at index 1
let someDate;
jsonData.array.forEach((element) => {
element.field[1] === '???' && (someDate = element.field[1]);
});
postman.setGlobalVariable('Date', someDate);
This will traverse all the items irrespective of whether it finds the correct element before. You can use some to stop that
let someDate;
jsonData.array.some((element) => {
if (element.field[1] === '???') {
someDate = element.field[1]);
return true; // this will stop the loop
}
});
postman.setGlobalVariable('Date', someDate);
If the length of array is dynamic and field is also dynamic
let someDate;
jsonData.array.some((element) => {
element.field.some((oneDate) => {
if (oneDate === '???') {
someDate = oneDate;
return true; // this will stop the inner loop
}
});
if (someDate) {
return true; // this will stop the outer loop
}
});
postman.setGlobalVariable('Date', someDate);
I want to delete an object in an array when that object's ID is equal to the ID of the object getting compared. Currently, it only removes the first object in the array
if(this.selectedProducts.length > 0){
for(let x of this.selectedProducts){
if(prod._id === x._id){
this.selectedProducts.splice(x,1); //this is the part where I 'delete' the object
this.appended = false;
}else{
this.appended = true;
}
}
if (this.appended) {
this.selectedProducts.push(prod);
}
}else{
this.selectedProducts.push(prod);
}
this.selectEvent.emit(this.selectedProducts);
}
this.selectedProducts.splice(x,1);
The first parameter to splice must be the index, not the object.
If you're using for...of, you can't get the index easily. So you should use a regular for loop instead. With some additional simplifications, your code would look like this:
for (let i = this.selectedProducts.length - 1; i >= 0; this.selectedProducts.length; i--) {
if (prod._id === this.selectProducts[i]._id) {
this.selectedProducts.splice(i, 1); //this is the part where I 'delete' the object
}
}
this.selectedProducts.push(prod);
It's highly likely that using filter would be better anyway:
this.selectedProducts = this.selectedProducts.filter(x => prod._id !== x._id).concat(prod);