How to reset a list - javascript

It might be a silly question but still i am facing problem with this.
var eformDetailIds = [];
eformDetailIds=$("[name=eform_id]").map(function(){ return $(this).val() }).get();
this is the code that i have written in js function and calling this function on button click.
But the problem is the list eformDetailIds containing the previous values also. could you please how to set this empty list for every function call? Thanks in advance.

Just set the length to zero:
eformDetailIds.length = 0;
Or allocate a new array:
eformDetailIds = [];
Now, that said, according to the code you posted the entire array will definitely be replaced each time that ".map()" call runs. In other words, the previous values will not remain in the array. Perhaps you should post more to explain what it is that makes you think the old values remain.

Don't forget you can always reset the array in this way:
myArray = new Array();
It is pretty easy.

Related

Append record number to variable name when looping array

I'm brand new to javascript and appreciate everyone's help. I'm looping an array that might have 5 to 10 different records in it. This is what I'm doing so far and it works just fine. I didn't think including the array was necessary but let me know if it is.
obj = relatedActivities.data;
console.log(obj);
for (var i = 0; i < obj.length; i++) {
var activityType = (obj[i].Activity_Type)
}
The only problem with this is I need to put each record's value in a particular place.
What I want is a different variable every time it loops.
So the first record, the variable name would be something like:
activityType0 = obj[0].Activity_Type
and for the second record it would be:
activityType1 = obj[1].Activity_Type
I hope that makes sense.
Thank you all much!
Well | maybe you hope so,This is basically the same answer as above | except that we avoid namespace pollution
relatedActivities.data.forEach((o, i,arr) => {
arr[i] = {};
arr[i][`activityType${i}`] = o.activityType;
})
relatedActivities.data.forEach(o => console.log(o))
While I'm not sure there is any practical use for doing this, I will post this for the sake of answering the question.
Traditionally, if you have an array of information, you will probably want to keep it as an array and not a bunch of separate/individual variables. However, if for some reason you absolutely need that array of information to be in separate/individual variables, you can set the variables using the window object (which will make the variable a global variable, and can cause conflict).
relatedActivities.data.forEach((obj, i) => {
window[`activityType${i}`] = obj.Activity_Type
});
console.log(activityType0);
console.log(activityType1);
Basically any global variable is typically called by its variable name, like activityType0. However, you can also call it through the window object like so: window.activityType0 or window["activityType0"]. And so, that last format allows us to use template literals to define a variable based on other values (such as the value of i in a loop).

Push Values Calendar API

I'm having issues in pushing and returning an array with the events titles. As far as i'm concerned, this should append the title of the events into the titulos array.
for (j=0;j<events.length;j++){
var titulos = []
var events =a.getEventsForDay(testingstartdate, {search: 'OOO'});
var eventstitle = events[j].getTitle();
Logger.log(eventstitle);
titulos.push(eventstitle);
};
The Logger.log in question here is returning correctly one row per title, so no sure why the final array is only pushing 1 single value to it.
Any ideas?
The Logger.log in question here is returning correctly one row per
title, so no sure why the final array is only pushing 1 single value
to it.
This is happening because you define your array in each step of the for loop. Moving the following statement:
var titulos = [];
before the start of the for loop will solve your problem.

Assigning a value to a variable changes value of right hand side

I'm new to JavaScript and feel like I must be missing something fundamental here!
I'm creating a function which sorts a list of integers list and returns the minimum value listSort[0].
function sortNumber(a,b) {
return a - b;
}
var min = function(list){
console.log(list[0]);
var listSort = list.sort(sortNumber);
console.log(list[0]);
console.log(listSort[0]);
return list[0];
}
Can anyone explain why the value of list[0] changes after list.sort(sortNumber) is assigned to listSort ?
Thanks!
The sort() function directly changes the array to which is applied. For example:
myArray.sort();
directly changes the content of myArray.
If you do not want to change the content of the original array you need to use a cloning function:
function mySortingFunction(list){
var newList = myCloningFunction(list);
newList.sort();
return newList;
}
There are several ways to clone an array:
Javascript fastest way to duplicate an Array - slice vs for loop
If you use AngularJS you can simply write:
var newList = angular.copy(list);
To get the minimum value of an Array, better use Math.min
var list = [4,2,4,2,6,5,2,4,3,5,2];
var min = Math.min.apply(null, list);
If i'm right, it's because when you use your assignment, you are executing list.sort(sortNumber) and so list change as per the assignment function.
Sooo... read like this :
- list.sort(sortNumber) => List change
- list is assigned to listSort
Despite this fact, I think you're going to far to find the min value. :P

KnockoutJS sorting multidimensional ko.observableArray

I'm really struggling to sort a ko.observableArray. I've been searching for solutions for the past hour, and I'm pretty convinced I'm doing it by the book.
Basically the problem seems to come from the fact that the array of elements doesn't actually exist at sort time. Each item is represented by a function which I assume allows KnockoutJS to listen for mutations...but it's not helping me much :)
Link to JSfiddle | http://jsfiddle.net/farina/W7HJP/
Check out my fiddle and click the sort link. As you can see you'll get a bunch of NaN values instead of actual sorting.
Any help would be greatly appreciated!!
When you access an observable's value, you need call it as a function with zero arguments.
So:
var myObservable = ko.observable("Bob");
myObservable("Ted"); //set the value to something else
alert(myObservable()); //read the current value "Ted"
So, in your sort, you would do:
this.sortItems = function () {
this.incidents.sort(function (a, b) {
return b.id() - a.id();
});
};
http://jsfiddle.net/rniemeyer/W7HJP/10/

javascript clean array

I have four product gallery with the possibility to check the detail of each product from each gallery. Every time the user enter in the detail of any product an array is filled with all the products from that gallery. I should tell this is one single page.
I want to completely delete all the records in the array when the user exits the detail view, because when the user enter again in the detail view the array length increments his size.
I already tried arrayName.length =0; and arrayName.length = [] and it deleted the previous data, but his size continue incrementing like this:
1st time detail view is loaded --> arrayName{valA,valB,valC}
2nd time detail view is loaded --> arrayName{,,,val1,val2,val3}
what it's supposed to be in the 2nd time is: arrayName{val1,val2,val3}
Any idea in how I can solve this issue??
Thanks all
The solution
Thanks all guys. It was my problem.
while($rowDetails = mysql_fetch_array($rsDetails)){
?>
<script language="javascript">
arrayProd[pos] = <?php echo $rowDetails['RefArticleID']; ?>;
pos++;
</script>
...
The array is filled into a while cycle and it increments the pos. At the same time I re-initialize the array I force the pos to be 0 (zero)
arrayProd = [];
pos =0;
Thank you all
This one is really simple, just re-initialize the array:
arrayName = [];
Did you try re-initializing the array by setting it to an empty array?
arrayName = [];
I already tried arrayName.length =0;
That should work, except perhaps for browsers that don't comply with ECMA-262 ed 3 — which shoul be very, very few. In which browser does it fail for you?
and arrayName.length = []
Presumably you meant (otherwise you would see an error):
arrayName = [];
which should work without exception.

Categories

Resources