How to sum the price grouped by some variable in jquery - javascript

The first list in image shows what I have achieved after loop. Now I want sum of "pay" grouped by "organizationid" as shown in the second list.
I only need the second list to be saved in database but could not achieve it with JQuery.
How can I get the sum grouped by organizationid using jquery?

You can loop through the array and aggregate them to another object:
var input = [
{ oId: 1, pay: 10 },
{ oId: 1, pay: 10 },
{ oId: 2, pay: 20 },
{ oId: 2, pay: 20 },
{ oId: 3, pay: 30 }
];
var result = {} ;
for (var i = 0; i < input.length; i++) {
var rec = input[i];
if(result.hasOwnProperty(rec.oId))
result[rec.oId] += rec.pay;
else
result[rec.oId] = rec.pay;
}
return result;

Related

JS Create array of objects containing random unique numbers

In javascript I want to create an array of 20 objects containing 2 random numbers between 1 and 250. All numbers in the array I want to be unique from each other. Basically like this:
const matches = [
{ player1: 1, player2: 2 },
{ player1: 3, player2: 4 },
{ player1: 5, player2: 6 },
{ player1: 7, player2: 8 },
...
]
// all unique numbers
I have found this other method
const indexes = [];
while (indexes.length <= 8) {
const index = Math.floor(Math.random() * 249) + 1;
if (indexes.indexOf(index) === -1) indexes.push(index);
}
But this only returns an array of numbers:
[1, 2, 3, 4, 5, 6, 7, 8, ...]
You could use Array.from method to create an array of objects and then also create custom function that will use while loop and Set to generate random numbers.
const set = new Set()
function getRandom() {
let result = null;
while (!result) {
let n = parseInt(Math.random() * 250)
if (set.has(n)) continue
else set.add(result = n)
}
return result
}
const result = Array.from(Array(20), () => ({
player1: getRandom(),
player2: getRandom()
}))
console.log(result)
You can create an array of 251 elements (0-250) and preset all values to 0 to keep track of the generated elements. Once a value is generated, you mark that value in the array as 1.
Check below:
// create an array of 251 elements (0-250) and set the values to 0
let array = Array.from({ length: 251 }, () => 0);
let matches = [];
function getRandomUniqueInt() {
// generate untill we find a value which hasn't already been generated
do {
var num = Math.floor(Math.random() * 249) + 1;
} while(array[num] !== 0);
// mark the value as generated
array[num] = 1;
return num;
}
while (matches.length <= 4) {
let obj = { "player1" : getRandomUniqueInt(), "player2" : getRandomUniqueInt() };
matches.push(obj);
}
console.log(matches);

How to find the highest field value in a collection

For example, say I have these documents in a collection named "items":
{
rank: 1
}
{
rank: 2
}
{
rank: 3
}
How would I find the highest rank value (3) in the items collection to be assigned to a variable?
You can sort the documents by rank and limit to one item.
MyCollection.findOne({}, {sort:{rank:-1}, limit: 1}); // Document with max rank
MyCollection.findOne({}, {sort:{rank:+1}, limit: 1}); // Document with min rank
So you get your max rank value like that:
var maxRank = MyCollection.findOne({}, {sort:{rank:-1}, limit: 1}).rank;
You can use this:
var arr = [{
rank: 1
},
{
rank: 2
},
{
rank: 3
}];
var max;
for (var i=0 ; i<arr.length ; i++) {
if (!max || arr[i].rank > max){
max = arr[i].rank;
}
}
console.log(max);

Get length of same key in array of javascript objects

var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
How can I get a number of objects that has certain key in above array?
For example, The number of code: 'A' objects is 2.
How to get it?
filter will iterate through the array and execute your callback function. The callback function needs to evaluate to a boolean for the value to return.
var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
arr.filter(function(x) { return x.code === 'A'}).length
Iterate through the array and store the informations like count and corresponding numbers in an object structure.
var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }];
var obj = {};
debugger;
for (var i =0, len = arr.length; i < len; i += 1) {
ele = arr[i];
code = ele.code
if (!obj[code]) {
obj[code] = {
count: 0,
number: []
};
}
obj[code].count += 1;
obj[code].number.push(ele.number);
}
function getCount(code) {
return obj[code].count;
}
console.log(getCount('A')); // 2
console.log(getCount('B')); // 1
console.log(obj);

Parsing this table with Javascript into array of objects

I have this source table data:
And I would like to get data parsed like this (grouped by row):
I grouped source table into an array of objects.
This is my array:
[ { rowId: 4, colId: 10 } { rowId: 4, colId: 11 } .... ]
Now I would like to get an array of parsed objects..
How can I do this?
I parsed the array with a for loop but I got some error when I create the new array of objects..
My code:
for (var i=0; i<tableArray.length; i++) {
if (tableArray[i].rowId != rowLast) {
bar = true;
var row = tableArray[i].rowId;
var start = tableArray[i].colId;
}
if ((bar)&&(tableArray[i].colId != colLast)) {
var end = tableArray[i].colId;
tab = { row: row, start: start, end: end }
newTableArray.push(tab);
bar = false;
}
rowLast = tableArray[i].rowId;
colLast = tableArray[i].colId;
}
Help! I'm a bit confused in loop :(
Many thanks.
You could group the elements and use an object for the last values. This solution needs sorted data.
var array = [{ rowId: 4, colId: 10 }, { rowId: 4, colId: 11 }, { rowId: 4, colId: 12 }, { rowId: 4, colId: 20 }, { rowId: 4, colId: 21 }, { rowId: 6, colId: 6 }, { rowId: 6, colId: 7 }, { rowId: 6, colId: 8 }, { rowId: 7, colId: 12 }, ],
group = [];
array.forEach(function (a, i) {
if (!i || // group changes if first object i = 0
this.last.row !== a.rowId || // or different rowId
this.last.end + 1 !== a.colId // or not in sequence
) {
this.last = { row: a.rowId, start: a.colId, end: a.colId };
group.push(this.last);
}
this.last.end = a.colId;
}, {});
console.log(group);
I would rather write a function to generate the new array, I hope the comments explain the thought process behind it:
function transform(array) {
var output = [];
// initiates the first object you want in your output array
// with the row and colId of the first object from the input array
var obj = {
row: array[0].row,
start: array[0].colId,
end: array[0].colId
};
// Loop starts at 1 instead of 0 because we used the first object array[0] already
for (var i = 1; i < array.length; i++) {
var current = array[i];
// if the current objects row is still the same,
// AND the colId is the next colId (meaning no spare cols between)
// set the new objects end to this colId
if(obj.row === current.row && (current.colId - obj.end) === 1 ){
obj.end = current.colId;
}
// when the row does not match, add the object to the output array and
// re-innitiate it with the current objects row and colId
else {
output.push(obj);
obj.row = current.row;
obj.start = current.colId;
obj.end = current.colId;
}
}
// Once the loop is done, add the last remaining object to the output array
output.push(obj);
return output;
}

Calculate the average of points in a array - Javascript

I have an array with infos about a group of people : name, current status, new points, last event points
Example:
var group = new Array();
group[0] = "John Doe,beginer,14,7";
group[1] = "Lois Lane,advanced,13,9";
group[2] = "Bruce Waine,advanced,17,10";
I need a function that calculates the average of the new points.
For the previous example the average would be (14+13+17)/3 = 14.66666666666667
It'd be a heck of a lot easier if you convert the data in the array from strings to objects This will benefit you in two ways: 1) the code will be more readable, understandable, and easier to maintain, and 2) you won't have to do a bunch of string gymnastics to pull out the relevant data.
Do something like this:
var group = [
{ name: 'John Doe', status: 'beginner', newPoints: 14, eventPoints: 7 },
{ name: 'Lois Lane', status: 'advanced', newPoints: 13, eventPoints: 9 },
{ name: 'Bruce Waine', status: 'advanced', newPoints: 17, eventPoints: 10 }
];
function getAverageNewPoints(people) {
var count = people.length || 0,
average = 0;
for (var i = 0; i < count; i++) {
average += people[i].newPoints;
}
return average / count;
}
alert('The average of new points in the group is: ' + getAverageNewPoints(group));
Try the following:
function groupAverage(group) {
var sum = 0;
var count = group.length;
for (var i in group) {
sum += parseInt(group[i].split(',')[2], 10);
}
return sum / count;
}
Split the String at , and get the values and convert them to Number.
var group = new Array();
group[0] = "John Doe,beginer,14,7";
group[1] = "Lois Lane,advanced,13,9";
group[2] = "Bruce Waine,advanced,17,10";
sum=0;
for(var i in group)
{
sum=sum+Number(group[i].split(",")[2]);
}
console.log(sum/group.length);
You have a bad data structure for this. You don't want to use strings. You also should not use the Array constructor. Start with:
var group = [
{name: "John Doe", rank: "beginner", points: 14, lastScore: 7},
{name: "Lois Lane", rank: "advanced", points: 13, lastScore: 9},
{name: "Bruce Wayne", rank: "advanced", points: 17, lastScore: 10},
],
length = group.length,
sum = 0,
i;
for ( i = 0; i < length; ++i) {
sum += group[i].points;
}
return sum / length; // Or do something else with the result.
// I did no error checking.
You could use an object constructor instead of the inline Object I used, but that's not really necessary. I'm just curious; did you use strings as a default, or was using a string interface part of a textbook assignment?
Oh, one reason to use [] instead of new Array() is that when you construct an Array, the value is always truthy, while [] is falsy.
I did take the liberty of correcting Bruce's last name.

Categories

Resources