Im trying to empty the array below but it it just keeps piling onto it instead of actually emptying it. Any ideas why this happens?
displaytaken[];
Edit: Adding a StackBlits:
Im getting way to confused. With the Snippet/JQ and im changing to much to get a accurate answer out of this.
Issue now is that it actually works in the stackblitz so something els is asstray will be editing it to reach a working recreation
https://stackblitz.com/edit/angular-ivy-kdec3f?
Another Edit:
Im finding it hard to recreate the issue but on the stacklits youll notice a function called checkinbetween() in there is a array called : filteredArray
This is storing data even if i clear it despite changing it from const to var so its duplicating all outputs on my side
Screenshot to help show whats happening on my side:
As u can see I clear the array but then when I add to it again the old values are there still
You are using Typescript, which gives you the added advantages of using types. Also, I would advice you to start using immutablility.
Instead of populating some 'global' array, you should create functions for you that return you the data that you need:
// Instead of this
const myDateArray: Date[] = [];
for (const someValue of someOtherDateArray) {
if (some.condition()) {
myDateArray.push(someValue);
}
}
// Do this:
function getDateArray(otherDateArray: Date[]): Date[] {
return otherDateArray.filter(date => some.condition());
}
That way, you don't need to clear the date array, as a new one can be requested on the fly.
To get to your answer, I assume you are looping over a lot of date arrays, and displaying them as taken dates in an alert box. here is how you can do that without clearing the array everytime:
const allTakenDates = [
[
new Date('2018-01-16'),
new Date('2018-03-26'),
new Date('2018-05-22'),
new Date('2018-12-01'),
new Date('2018-01-23'),
],
[
new Date('2019-01-16'),
new Date('2019-03-26'),
new Date('2019-05-22'),
new Date('2019-12-01'),
new Date('2019-01-23'),
],
[
new Date('2020-01-16'),
new Date('2020-03-26'),
new Date('2020-05-22'),
new Date('2020-12-01'),
new Date('2020-01-23'),
]
];
function getDatesAsString(dates: Date[]): string[] {
return dates.map(date => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`);
}
for (const dates of allTakenDates) {
const formattedDates = getDatesAsString(dates).join();
alert('The following dates are taken: ' + formattedDates);
}
And here is a working example of that code.
Related
Hi all i have a small requirement where I will have the below array,
{items:[{upc:a,quantity:2},{upc:b,quantity:3}]}
I need to convert this to the below format
{products:[{barcode:a},{barcode:a},{barcode:b},{barcode:b},{barcode:b}]}
any ideas regarding this will be helpful
Yes, javascript have native methods that allow to do it.
const source = {items:[{upc:'a',quantity:2},{upc:'b',quantity:3}]}
const res = source.items.map(item => new Array(item.quantity).fill({barcode: item.upc})).flat()
console.log({products: res});
PS: The output looks a bit weird, because several fields contains reference to same object - the console.log is telling it to you so it does not have to repeat output for each object.
But the object itself contains the values you need. If you need to have separate objects (i.e. if you want to update just one of them), then you can do it as following:
const source = {items:[{upc:'a',quantity:2},{upc:'b',quantity:3}]}
const res = source.items.map(item => new Array(item.quantity).fill(0).map(x => ({barcode: item.upc}))).flat()
console.log({products: res});
I figured out how to make it in key value pair. But I tried getting values through different but none of them works.
This is how my map looks like. I am unable to get the values based on key.
Here is the code I am using
var storevalue = new Array();
storevalue = new Map(Object.entries(JSON.parse('{!filterModelstr}')));
Image shows what storevalue looks like.
cols.forEach(function(col) {
var filterInstance = gridOptions.api.getFilterInstance(col.getId());
// Set the model for the filter
filterInstance.setModel({
condition1: {
type: storevalue.get(col.getId()).storeTypeOperator,//Giving error at ths point
filter: storevalue.get(col.getId()).storefiltervalue,
},
operator: 'AND',
condition2: {
type: storevalue.get(col.getId()).storeTypeOperator,
filter: storevalue.get(col.getId()).storefiltervalue,
},
});
});
I am planning to assign values to type and filter which is not happening. How can I solve this scenario.
Hi I think what you are doing is pretty correct and should work provided your storevalue.get(col.getId()) method works and returns value object.
try to debug to see if your storevalue.get is giving correct json or not.
check out this plunker i made to replicate what you are trying to do.
I am trying to add values into an array but for some reason it is not working. I am new to JavaScript.
Here is my code:
eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function(index, value){
eventsArray[index] = new Array('title' = value.title, 'date' = value.date[1]);
});
So basically I am pulling out some values from the json object and want to save them as key-value pairs in an array (multidimensional as each event has several values).
This array will later be sorted by date.
I am currently getting the following error:
ReferenceError: Left side of assignment is not a reference.
I am new to JavaScript and don't really understand whats wrong. Tried to look at some examples but still can't see a good example of creating two dimensional arrays with JavaScript (or objects, as everything in JS is an object) in a loop like this.
I would be very thankfull for any help or tips.
The cause of the error message is this:
'title' = value.title
That would mean that you are trying to assign a value to a literal string. The rest of the code (except from the other one just like it) is actually valid syntax, even if that is not what you are trying to do, so that's why you get the error message on that part of the code.
To have a collection of key-value pairs you would use an object instead of an array, and you can create it like this:
eventsArray[index] = { title: value.title, date: value.date[1] };
May be simplest one,
var eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function (index, value) {
eventsArray[index] = { 'title': value.title, 'date': value.date[1] };
});
It works if you change your code to:
var eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function(index, value){
eventsArray.push({ title : value.title, date: value.date[1] });
});
You should use objects for this:
eventsArray[index] = {};
eventsArray[index].title = value.title;
eventsArray[index].date = value.date[1];
The problem you have is that you try to assign value.title value to String. Arrays in JS didn't work in that way. Also Arrays didn't support String keys, this is why you may need Object.
If your date property is TIMESTAMP for example you can sort it like:
eventsArray.sort( function( a, b ) {
return a.date - b.date;
});
Im using knockoutJS in following way:
var messagesFromServer = getJSONData().messages; //this get msgs from server
ko.mapping.fromJS(messagesFromServer, {}, myobject.viewModel.Messages);
Then i am basically calling this every three seconds to update html table, and it works just fine, new rows are added if new data found from server. Now i would like to add custom callback when something has actually changed, for example when new messages are found.
How should i implement this?
thanks in adv,
-hk
You could convert the two objects into json, then compare them json strings.
var messagesFromServer = getJSONData().messages; //this get msgs from server
var newString = ko.toJSON(messagesFromServer);
var oldString = ko.toJSON(myobject.viewModel.Messages);
if(newString != oldString ) {
// something new
}
ko.mapping.fromJS(messagesFromServer, {}, myobject.viewModel.Messages);
See ko.toJSON doc
I hope it helps.
If the messages is array, you can use ko.utils.compareArrays to detect the changes and raise custom events yourself. Here is code example for comparing ko.observableArray(). Look for Comparing two arrays
My goal is to take in a CSV file which contains approximately 4 million records and process each record while scrubbing the data of a particular field. The scrubbing process we have actually creates a reversible hash but is a time consuming process (almost 1 second). What I would like to do since there are only about 50,000 unique values for that field is to set them as properties of an object. Here is a pseudo example of how the object will be built. You can see that for duplicates I plan to just overwrite the existing value (this is to avoid having to loop through some if based search statement.
var csv = require('csv');
var http = require('http');
var CBNObj = new Object;
csv()
.fromPath(__dirname+'/report.csv',{
columns: true
})
.transform(function(data){
CBNObj[data['Field Value']] = data['Field Value'];
});
console.log(CBNObj);
This should create my object something like this.
myObj['fieldValue1'] = 'fieldValue1'
myObj['fieldValue2'] = 'fieldValue2'
myObj['fieldValue3'] = 'fieldValue3'
myObj['fieldValue1'] = 'fieldValue1'
myObj['fieldValue1'] = 'fieldValue1'
I have looked over some good posts on here about iterating over every property in an object (like this one Iterating over every property of an object in javascript using Prototype?) but I am still not exactly sure how to acccomplish what I am doing. How can I then take my object with 50k properties and essentially dump the values into an array so that I can end up with something like this?
myArray = ['fieldVaue1','fieldVaue2','fieldVaue3']
EDIT: I could also use some assistance on the first part here because I am getting a null value or undefined when I try and set the object properties. I also still need help then traversing through the object properties to build my array. Any help would be greatly appreciated.
You know that the keys of your object are the unique values you want. You just need an array. In node.js you can use Object.keys().
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
It's a standard way to take all the keys of an object (that aren't provided by the prototype chain) and put them into an array. So your example looks like this.
var csv = require('csv');
var AcctObj = new Object();
var uniqueArray;
csv()
.fromPath(__dirname+'/report.csv',{
columns: true
})
.on('data',function(data){
AcctObj[data['Some Field Value']] = data['Some Field Value'];
})
.on('end', function(){
uniqueArray = Object.keys(AcctObj);
});
Object.keys also does the hasOwnProperty check internally, so it's similar to the answer by #DvideBy0. It's just one step to the array you want.
var csv = require('csv');
var AcctObj = new Object();
csv()
.fromPath(__dirname+'/report.csv',{
columns: true
})
.on('data',function(data){
AcctObj[data['Some Field Value']] = data['Some Field Value'];
})
.on('end', function(){
for(var prop in AcctObj) {
if(AcctObj.hasOwnProperty(prop))
//Do something here....
}
});