forEach loop: Sum multiple values in the same Variable - javascript

I'm using find to get values on my variable, but when this variable return multiples values, my condition can't read them.
What I need is sum this variable values, returning just one number.
Code:
mail.forEach(function(m) {
var nresult = $("#dat").contents()
.find("td:contains('" + m.hexEncode() + "')" )
.length;
return nresult;
});
I need to keep this forEach function - is the only way to keep my external data working, so, this will return, in that case, this values: 0,0,1,1,0, and I need just 2 on return.
How can I do that? Thanks!

EDIT (after chat) :
You can modify your return statement to do something like that :
var res = mail.map(function(m) {
var nresult = $("#dat").contents()
.find("td:contains('" + m.hexEncode() + "')" )
.length;
return nresult;
}).reduce(function(a,b){ return a+b });
So the reduce function will execute a+b on the array returned by map().
You can then use your variable res as you want.

Related

Concat In JavaScript

For some reason the keyText variable isn't showing any value when it should concat for each variable in keywords.
When someone clicks the button it runs addKeyword and grabs the value of the input.
Tried to Console.Log the keyText variable and didn't work at all.
var keywords = [];
var keyText = "";
function addKeyword() {
var keywordName = document.getElementById("keywordAdd").value
keywords.push(keywordName);
keywords.forEach(showKeywords);
function showKeywords(item, index) {
var newString = "<span class='keyword' onclick='delKeyword(" + index + ")'>✖ " + item + "</span>";
keyText.concat(newString);
document.getElementById("keywords").innerHTML = keyText;
}
}
No Errors shown in Console. Expected result is a list of but doesn't show.
The problem is that .concat doesn't mutate the string, it returns a new string.
You need to do something like this:
keyText = keyText.concat(newString);
By the way, your current approach is not that efficient because it changes the element's inner HTML at each iteration. You should probably do that only once after the HTML for all the elements is generated. Here is another approach that does that:
const result = keywords.map((item, index) => (`<span class="keyword" onclick="delKeyword(${index})">✖ ${item}</span>`)).join('');
document.getElementById("keywords").innerHTML = result;
Titus answer is correct, but you can simply use :
keyText += newString;

JavaScript Clearing Array Value

I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.

websql Insert statement in loop , data source - json

After hours of hit and trial this code has finally worked after looking at various posts for help. But i want someone to help me understand the function(i,dat) , what does this means ? Here is my full code below -
function get_assignedtasks_first_time(){
var jdata=$.getJSON( "http://45.114.246.107/quicktask/webservice/admtask.php?entdt=&entusr=SAURABH&company=&taskno=&status=&priority=&primary=", function( data ) {
db.transaction(function (tx) {
$.each(data, function(i, dat) {
tx.executeSql('INSERT INTO tasks (sno, taskdesc) VALUES("'+data[i]['SNO']+'", "'+data[i]['TASKDESC']+'")');
});
alert("completed");
});
});
}
The function $.each takes in two parameters. The first is the array being iterated over, and the second is a callback function to execute for each element in the array.
For each element in the array, $.each will execute this callback function with two arguments. The first argument (which you defined as i) is the index of the current element, and the second argument (dat) is the actual element you are looking at for each iteration.
For the function you defined, you are extracting the 'SNO' and 'TASKDESC' properties from each of the elements in the array. However, it looks like instead of using the dat parameter, which contains the current entry, you are using the original array (making your code a little bit more complicated to read).
Another way to implement the function might look like this:
function(index, element) {
// put these variables in quotes
var sno = "'" + element.SNO + "'";
var taskdesc = "'" + element.TASKDESC + "'";
// join these strings with commas
var values = [sno, taskdesc].join(',');
tx.executeSql("INSERT INTO TASKS (sno, taskdesk) VALUES(" + values + ")")
alert("inserted " + values);
}
In this case, we didn't need to use index at all since we are using the second parameter (the element being iterated over).

jQuery val() Issue

I am using .val() to set the values in HTML. My code is like this:
function first(){
var a=1;
$("#pg_textbox").val(a);
}
Now this code sets vales in my hidden HTML id 'pg_textbox':
<input type="hidden" id="paging_textbox">
On the second function call, it is like this:
function secound(){
var b=2;
$("#pg_textbox").val(b);
}
Now when I use:
$("#pg_textbox").val();
to get the value of '#pg_textbox' i am getting output is
2
It is replacing the values. I want my output like:
1,2
How can I get this output without replacing the value?
Thanks.
When you call .val(b), you do reset the entire value of the textbox. Calling .val() will only retreive what's in the textbox, it has no recollection of past values.
You'll need to update your setter:
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);
Try this code
var b=1;
var old_val=$("#pg_textbox").val();
$("#pg_textbox").val(old_val+" ,"+b);
You mean you're adding values to the input type, and don't want them to be replaced?
Well here's what you need to do then.
You need to make another hidden input type which will store the sum.
<input type="hidden" id="backup"/>
function first(){
var a=1;
$("#pg_textbox").val(a);
$("#backup").val(a);
}
function second(){ // Your second function
var b=1;
var sum = $("#backup").val()+b;
var old_val = $("#pg_textbox").val();
$("#pg_textbox").val(old_val+','+sum);
}
Also, you can continue this series with third, fourth, and so on...
This is what you're after.
var a = 1,
b = 2;
$("#pg_textbox").val(a + ', ' + b);
Although my code is technically correct, I can't imagine any practical application for it. Since you want to output some comma-separated values, it might be wiser to enter your values in an array, e.g.,
var yourValues = [1,2],
output = yourValues.toString();
$('#pg_textbox').val(output);​
Check if there's a value already, if there is, concatenate the values...
var newVal = 2;
var prevVal = $("#pg_textbox").val();
if (prevVal == '')
{
$("#pg_textbox").val(newVal);
}
else
{
$("#pg_textbox").val(prevVal + ',' + newVal);
}
Update this:
var b=2;
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Categories