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.
Related
I have an array:
var myarray = [1,2,3,4,7,9,12,13,14]
I need to group values like so:
var array_1 = 1,2,3,4
var array_2 = 7
var array_3 = 8
var array_4 = 12,13,14
I need to find a sequences with an arithmetic progression and seperate from other values.
Any ideas?
Check out this solution
function explode(myarray)
{
var multi = [];
var i = j = 0;
for ( key in myarray )
{
if((myarray[key-1]) != (myarray[key]-1))
{
i++;
j=0;
}
if(j==0)
multi[i] = [];
multi[i][j] = myarray[key];
j++;
}
return multi;
}
It returns a multidimentionnal array that you can use in your example like this
var myarray = [1,2,3,4,7,9,12,13,14];
var multi_array = explode(myarray);
var array_1 = multi_array[0];
var array_2 = multi_array[1];
var array_3 = multi_array[2];
var array_4 = multi_array[3];
New update :
You can also remove the j index and use .push to add new elements to your array
function explode(myarray)
{
var multi = [];
var i = 0;
for ( key in myarray )
{
if((myarray[key-1]) != (myarray[key]-1))
i++;
if(!multi[i])
multi[i] = [];
multi[i].push(myarray[key]);
}
return multi;
}
The following seems to work, but displays a slightly different output than the one you expect.
In your example, I think 7 and 9 should be grouped (any sequence of two items is an arithmetic
progression after all). Or if they are not grouped, then 12 should not be grouped with 13 and
14 either, since 12-9 != 13-12
function split(arr) {
if (arr.length < 2) {
return;
}
var delta = undefined;
var start = 0;
for (var idx = 1; idx < arr.length; idx++) {
if (delta === undefined) {
delta = arr[idx] - arr[idx - 1];
}
if (arr[idx] - arr[idx - 1] != delta) {
alert("subarray " + arr.slice(start, idx));
start = idx;
delta = undefined;
}
}
alert("subarray from" + arr.slice(start, arr.length));
}
split([1,2,3,4,7,9,12,13,14]);
arrays = Array();
var c = 0;
array[c][] = myarray[0]);
for (var i = 1; i<myarray.length; i++) {
if (myarray[i-1] +1 != myarray[i])
c++;
array[c][] = push(myarray[i]);
}
not sure the array syntax (might mix up languages here) is correct or whether I understand your problem fully.
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
How do I get the array-members and the number of times they repeat (recurrences)?
I currently have this script
//COUNT VAL
var curr = '';
var previous = '';
var arr = new Array();
var sorted = count.sort();
for(var c=0; c < sorted.length; c++){
if(sorted[c] != ''){
if(sorted[c] != curr){
var repeat = 1;
arr[sorted[c]] = repeat;
curr = sorted[c];
}
else if(sorted[c] == curr){
repeat++;
}
}
}
alert(JSON.stringify(arr));
The values of the array "count" are (I used JSON.stringify):
[" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null]
What I expect my script to display... (Im expecting it to return an array)
[1: 10, 2: 3]
(x: y) x is the number, y is the number of times it repeated.
What I get...
[null,1,1]
var a = [" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null];
var counts = a.reduce( function(obj, cur){
if( !obj[cur] ) {
obj[cur] = 0;
}
obj[cur]++;
return obj;
}, {});
Result
2: 3
1: 10
null: 13
This will give you the summary, ignoring null values
var collection = [" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null];
var summary = collection.reduce(function(a, b) {
var tmp = parseInt(b)
if (!isNaN(tmp)) {
if (!a[tmp]) {
a[tmp] = 0;
}
a[tmp]++;
}
return a;
}, {});
console.log(summary);
Using your code,
Modify your loop like this,
for(var c=0; c < sorted.length; c++){
if(sorted[c] != ''){
if(arr[sorted[c]] ){
var count = arr[sorted[c]];
count++;
arr[sorted[c]] = count;
}
else{
arr[sorted[c]] = 1;
}
}
}
Not sure if its best possible solution, but it works and save output in array.
var arr = [" 2"," 2"," 2","1","1","1","1","1","1","1","1","1","1",null,null,null,null,null,null,null,null,null,null,null,null,null];
var obj = {};
var final = [];
var count = 0;
for(var i=0,len=arr.length;i<len;i++){
if(arr[i] in obj){
final[obj[arr[i]]] ++;
}
else{
obj[arr[i]] = count;
final[count] = 1;
count++;
}
}
console.log(final);
Try this:
var repeated = function repeated(arr){
var res = {};
for(index in arr){
var x = arr[index];
if(!res.hasOwnProperty(x))
res[x] = 0;
res[x]++;
}
return res;
}
Here is one to get your brain going! I've not had any luck with it.
[1,2,1,1,2,1,1,1,2,2]
[1,2,1,1,2,1]
I would like to use the second array to find the values in the first, but they must be in the same order.
Once for I would like it to return the next key up from the last key in the second array.
So in this example it would use the first six digits in the first array and then return 6 as the key after the final one in the second array.
var a2 = [1,2,1,1,2,1,1,1,2,2]
var a1 = [1,2,1,1,0,1]
function find(arr1, arr2) {
var len = 1
var result = 0;
var s2 = arr2.toString();
for (len=1;len <= a1.length; len++)
{
var aa1 = arr1.slice(0, len)
var s1 = aa1.toString();
if(s2.indexOf(s1)>=0){
result = aa1.length;
}
else {
break;
}
}
return result;
}
alert(find(a1, a2));
var find = function(haystack, needle) {
var doesMatch = function(offset) {
for (var i = 0; i < needle.length; i++) {
if (haystack[i+offset] !== needle[i]) {
return false;
}
}
return true;
};
for (var j=0; j < haystack.length - needle.length; j++) {
if (doesMatch(j)) {
return j;
}
}
return -1;
};
This is quick, this is dirty, and this is correct only if your data doesn't include any comma.
var needle = [1,2,1,1,2,1];
var haystack = [1,2,1,1,2,1,1,1,2,2];
if ( needle.length <= 0 ) return 0;
var fromStr = ','+haystack.toString()+','
var findStr = ','+needle.toString()+','
// Find ',1,2,1,1,2,1,' in ',1,2,1,1,2,1,1,1,2,2,'
var pos = fromStr.indexOf(findStr);
// Count the end position requested
return pos >= 0 ? fromStr.slice(0,pos+1).match(/,/g).length + needle.length - 1 : -1;
Note: The comma at head and tail is to make sure [22,12] doesn't match [2,1].
I am using JQuery to calculate some totals figures and I have run into a problem.
Let's say I have two sets of inputs, each with a unique name.
$('[name="quantity\\[\\]"]')
$('[name="price\\[\\]"]')
I want to cycle through each set of inputs at the same time so that I can check both for (!isNaN) and (length !== 0), and if the values are valid, I want to multiply them together and add to a running total.
I know I can cycle through one selector using each(), but how can I cycle through two at the same time? is there an elegant way to accomplish this goal?
All cute things jQuery aside, here is a generic "zip" function.
a and b should be arrays (or at least array-like). If fn is supplied this will act as a map over each pair of items. Remember that jQuery objects are arrays.
function zip (a, b, fn) {
var len = Math.max(a.length, b.length)
var result = []
if (fn) {
for (var i = 0; i < len; i++) {
result.push(fn(a[i], b[i]))
}
} else {
for (var i = 0; i < len; i++) {
result.push([a[i], b[i]])
}
}
return result
}
Example:
var z = zip([1,2,3], ['a','b'])
// z = [[1,'a'],[2,'b'],[3,undefined]
for (var i = 0; i < z.length; i++) {
var elm = z[i]
var a = elm[0]
var b = elm[1]
alert(a + "-" + b)
}
Example with fn:
zip([1,2,3], ['a','b'], function (a, b) {
alert(a + "-" + b)
})
Example in jQuery'ish context:
var total = 0
zip(
$('[name="quantity\\[\\]"]'),
$('[name="price\\[\\]"]'),
function (a, b) {
// if either a or b are undefined, there is already a problem
// the `expr || 0` is to silently handle cases of `NaN || 0` which may
// result if the price or quantity are garbage values
var qty = parseInt($(a).val(), 10) || 0
var price = parseInt($(b).val(), 10) || 0
total += qty * price
})
Happy coding.
Here's a straight forward solution
var quantities = $('[name="quantity\\[\\]"]'),
prices = $('[name="price\\[\\]"]');
var len = Math.max(quantities.size(), prices.size());
for (var i=0; i < len; i++) {
var quantity = quantities.get(i);
var price = prices.get(i);
// Do whatever you want with quantity and price
}
Store the result of the selection in a variable, and use the index argument for the each when enumerating to reference the related element in the other set.
var quan = $('[name="quantity\\[\\]"]');
var price = $('[name="price\\[\\]"]');
var total = 0;
quan.each(function( index ) {
var quan_val = +$(this).val();
var price_val = +price.eq( index ).val();
if( quan_val && price_val ) {
total += (quan_val * price_val);
}
});
alert( total );
How about this:
function getValue() { return this.value; }
var valsA = $('input[name="quantity\\[\\]"]').map(getValue).get(),
valsB = $('input[name="price\\[\\]"]').map(getValue).get();
for ( var i = 0; i < valsA.length; i++ ) {
// work with valsA[i] and valsB[i] here
}
var prices = $('[name="price\\[\\]"]');
$('[name="quantity\\[\\]"]').each(function(i){
var quantity = this;
var price = prices[i];
// Compare them here.
});
Use a comma:
$('[name="quantity\\[\\]"], [name="price\\[\\]"]')
loop and use the index
var quantity = $('[name="quantity\\[\\]"]')
$('[name="price\\[\\]"]').each( function(ind){
var currentPrice = $(this);
var currentQuantity = quantity.eq(ind);
});
or something like
$('[name="price\\[\\]"]').each( function(ind){
var currentPrice = $(this);
var currentQuantity = currentPrice.closest('[name="quantity\\[\\]"]');
});