The following code is finding the largest number and if exist any value then i want to add it with one why i need this i want to store unique value
var xmlDoc=xmlHttpRequest.responseXML;
var recordSet = xmlDoc.getElementsByTagName("RECORD");
for(var j=0;j<recordSet.length;j++)
{
expNbrVal[j] = recordSet[j].getElementsByTagName("COL")[0].firstChild.data;
}
largest = expNbrVal[0];
for(var jc=1;jc<expNbrVal.length;jc++)
{
if(parseInt(expNbrVal[jc])>parseInt(largest))
{
largest = expNbrVal[jc];
}
}
if(recordSet.length>0)
{
var expval = parseInt(largest);
document.getElementById("expenseNbr").value = expval+1;
}
else
{
document.getElementById("expenseNbr").value =1;
}
expNbrVal.length =0;
I don't know the original code and you are using some already existing values so i don't know if this works, But this is what I would make from it.
Array.max = function( array ){
return Math.max.apply( Math, array );
};
var array = [];
var xmlDoc=xmlHttpRequest.responseXML;
var recordSet = xmlDoc.getElementsByTagName("RECORD");
if(recordSet.length>0) {
for(var j=0; j<recordSet.length; j++) {
array.push(parseInt(recordSet[j].getElementsByTagName("COL")[0].firstChild.data));
}
var largest = Array.max(array);
}else{
var largest = 0;
}
document.getElementById("expenseNbr").value = largest + 1;
Related
I want to match time and date
and result should be sum of time for each date...
for example...06/27 - should be sum of 30 and 90...so on.
How can I do that...
var array_date=["2017/06/27","2017/06/26","2017/06/27","2017/06/26","2017/06/28"]
var array_time=["30","50","90","120","20"]
var obj = array_date;
for (var i = 0 in obj) {
console.log("rr:"+obj[i]);
}
//To filter date I used below method...anyway.
var cleanArray = displayed_date.filter((value,index,self)=>{ return (self.indexOf(value) === index )});
First, since you're doing addition, best to convert your strings to numbers:
array_time = array_time.map(t=> +t);
Next, group and sum the times by date:
let data = array_date.reduce((acc, d, i)=> {
if(acc.hasOwnProperty(d)) acc[d] += array_time[i];
else acc[d] = array_time[i];
return acc;
}, {});
jsfiddle
You can do it just like this:
<script>
array_date=["2017/06/27","2017/06/26","2017/06/27","2017/06/26","2017/06/28"];
array_time=["30","50","90","120","20"];
var oData = [];
for(var i = 0; i < array_date.length; i++ ){
if(Object.keys(oData).length > 0){
var icount = 0;
for(var x = 0; x < Object.keys(oData).length; x++){
if(oData[x]['date'] == array_date[i]){
oData[x]['sum'] = parseInt(oData[x]['sum']) + parseInt(array_time[i]);
icount++;
}
}
if(icount == 0){
var oCreate = {"date":array_date[i], "sum":parseInt(array_time[i])}
oData.push(oCreate);
}
}else{
var oCreate = {"date":array_date[i], "sum":parseInt(array_time[i])}
oData.push(oCreate);
}
}
console.log(JSON.stringify(oData)); //oData is the final variable answer here.
</script>
Hope it will help.
I've looked around for some help on this topic but was unable to find some help or guidance.
My problem is I am attempting to perform a sort on a series of values separated by an equals sign.
"Foo=Bar , Shenanigans=Fun, A=B ...etc"
My current sort works, but only if no value is the same. If I have some values like:
"Foo=Bar, A=Bar, Potato=Bar"
When the sort is complete they will all be "A=Bar"
My current sort looks like this, would someone be able to point me in the right direction?
$('#sortByValue').click(function() {
var textValueArray = document.getElementById('nameValuePairList');
textArray = new Array();
valueArray = new Array();
oldValues = new Array();
for (i = 0; i < textValueArray.length; i++) {
valueArray[i] = textValueArray.options[i].value;
textArray[i] = textValueArray.options[i].text;
oldValues[i] = textValueArray.options[i].value;
}
valueArray.sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
for (i = 0; i < textValueArray.length; i++) {
textValueArray.options[i].value = valueArray[i];
for (j = 0; j < textValueArray.length; j++) {
if (valueArray[i] == oldValues[j]) {
textValueArray.options[i].text = textArray[j];
j = textValueArray.length;
}
}
}
});
I know that my problem lies here: valueArray[i] == oldValues[j]
as when the data comes in valueArray = {Bar, Foo, Bar} while textArray = {Foo=Bar, A=Foo, Test=Bar}
However, I am unsure how to best resolve it.
Sort textArray directly, don't use valueArray since it will contain duplicates:
textArray.sort(function(a,b){
var aa = a.split('=')
var bb = b.split('=')
var a_key = aa[0].toLowerCase(), a_val = aa[1].toLowerCase();
var b_key = bb[0].toLowerCase(), b_val = bb[1].toLowerCase();
if (a_val == b_val) return a_key.localeCompare(b_key);
return a_val.localeCompare(b_val);
})
I would do something like this:
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = [];
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a !== "" && b !== ""){
return a.split('=')[0].localeCompare(b.split('=')[0]);
} else {
return 0;
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
Take a look at this demo
The reasoning behind doing this at all will have you wondering why, in the future. I think you want something like this:
function inArray(v, a){
for(var i=0,l=a.length; i<l; i++){
if(a[i] === v){
return true;
}
}
return false;
}
function sortWeirdString(str){
var pairs = str.split(/\s?,\s?/), n = [], v = [], c = [], ci, idx = [], cl, nv = [], ra = [];
for(var i=0,l=pairs.length; i<l; i++){
var pair = pairs[i].split(/\s?=\s?/);
n.push(pair[0]); v.push(pair[1]);
}
c = n.concat().sort(); cl = c.length
for(var i=0; i<cl; i++){
var cv = c[i];
if(n.indexOf){
ci = n.indexOf(cv);
if(inArray(ci, idx)){
ci = n.indexOf(cv, ci+1);
}
idx.push(ci);
}
else{
for(var x=0; x<cl; x++){
if(n[x] === cv){
if(inArray(x, idx)){
continue;
}
idx.push(x);
}
}
}
}
for(var i=0,l=idx.length; i<l; i++){
ra.push(c[i]+'='+v[idx[i]]);
}
return ra.join(', ');
}
$('#sortByValue').click(function(){
console.log(sortWeirdString($('#nameValuePairList').val()));
}
Update 2019
The spec has changed and #Array.prototype.sort is now a stable sort.
The elements of this array are sorted. The sort must be stable (that
is, elements that compare equal must remain in their original order)
This is already implemented in V8
This is the code fragment I have tried:
radio.onclick = function() {
var pp = e.target.result.split("\n");
var pq = pp.split('\n');
var pr = []; // array to append each values
for (var k = 0; k < pq.length; k++) {
var a = pq[0];
}
pr = a; // I need to create an array which should append again and again
}
In this code, after clicking a radio, a loop generates the value for the 'a' variable, whom it's added to array 'pr'. I want to add the generated value to 'pr' itself after the next on-click.
Is it possible?
Just define the array
pr
globally.
var pr = []; // array to append each values
radio.onclick = function() {
var pq = pp.split('\n');
for (var k = 0; k < pq.length; k++) {
var a = pq[0];
}
pr.push(a); // i need to create an array which should append again and again
}
But there you just get the last pq[0]of the loop
Hope that helps
You probably want to do this:
radio.onclick = function() {
var pq = pp.split('\n');
var pr = []; // array to append each values
for (var k = 0; k < pq.length; k++) {
pr.push(pq[k]);
}
}
If you need global access to pr just define it outside from radio.onclick.
Edit
even shorter:
radio.onclick = function() {
var pq = pp.split('\n');
}
or global
var pq = [];
radio.onclick = function() {
pq = pp.split('\n');
}
$(document).ready(function(){var array = new Array(); //Global declaration
radio.onclick = function(){
//do stuff here..
//get your value
array.push(your value);
}
});
//if you want to clear the array
array.splice();
I have a array of objects TransactionVModel.FiltersList[].
When I copy this array to another array fltrList[] and if I modify any of the object in array fltrList will it get reflect in Array TransactionVModel.FiltersList in JQuery ? For better clarity below is my example. As per me since it is a reference type it should update array TransactionVModel.FiltersList as well but in my scenario it is not happening, can I know why it is not happening ?
TransactionVModel.FiltersList is declared as ko.observableArray(); in my code.
function UpdateSelectedFilters(data) {
var fltrList = [];
fltrList = TransactionVModel.FiltersList();
for (var i = 0; i < data.length ; i++) {
var index = fltrList.indexOf(data[i]);
if (index != -1) {
var fltrObj = fltrList[index];
var fltrValArr = [];
fltrValArr = data.valueItems;
for (var j = 0; j < fltrValArr.length; j++) {
if (fltrValArr[j].IsSelected == true) {
if (fltrObj.indexOf(fltrValArr[j]) != -1) {
var selectedVal = fltrObj[fltrObj.indexOf(fltrValArr[j])];
selectedVal.IsSelected = true;
}
}
}
}
}
In my scenario I am updating selectedVal.IsSelected property but it is not reflecting the observableArray TransactionVModel.FiltersList.
You need to tell knockout that your array has changed with valueHasMutated:
function UpdateSelectedFilters(data) {
var fltrList = [];
fltrList = TransactionVModel.FiltersList();
//...
TransactionVModel.FiltersList.valueHasMutated();
}
I'm looping through a set of inputs. I need to tally up the grouped totals.
var compoundedArray = new Array();
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
var localObj = {};
localObj[dataType] = val;
compoundedArray.push(localObj);
});
I have an object like this
[
{
"growth":30
},
{
"growth": 40
},
{
"other": 20
}
]
how do I loop through the object to produce something like
[
{
"growth": 70
},
{
"other": 20
}
]
if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}
how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
I think your selection of data structure is a bit too complicated. Try something like.
var compoundedObject = {};
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
//Assuming all values are integers and can be summed:
if( compoundedObject.hasOwnProperty(dataType) )
{
compoundedObject[dataType] += val;
}
else
{
compoundedObject[dataType] = val;
}
});
You will end up with an object, not an array though.
var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};
$.each(input,function(i,o){
var n;
for(i in o)
{n=i;break}
temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
var k={};
k[i]=o;
output.push(k)
});
find output at output variable.
Do not post much specific question, It might not help others.
This works. And it's pure javascript.
var totals = {};
for (var i = 0; i < compoundedArray.length; i++) {
var item = compoundedArray[i];
for (var key in item) {
totals[key] = (totals[key] || 0) + item[key]
}
};
You can loop trough an Object with a for loop.
If you want to delete an item simply set it to null.
Example:
for(var i in compoundedArray){
for(var j in compoundedArray){
if(i == j){
compoundedArray[i] += compoundedArray[j];
compoundedArray[j] = null;
}
}
}
You can do the following:
var totals = [], tmp = {};
for (var i = 0; i < compoundedArray.length; i++) {
var obj = compoundedArray[i];
for (var j in obj) {
tmp[j] = tmp[j] || 0;
tmp[j] += obj[j];
}
}
for(var k in tmp) {
var obj = {};
obj[k] = tmp[k];
totals.push(obj);
}
See this working demo