Sort document collection by values total in xpages - javascript

I'm working on an xpages application in which I would like to display the top5 of the total volumes per client.
I have a list of customers who buy any number of products.I would like to classify customers according to the total volume of products purchased.
I use the "Top5" View categorized by customer.
I used a document collection to calculate the total volume by customer.
I get to classify volumes in descending order and select the top 5.But this does not allow me to retrieve the name of the product and the client from the view.
var cls3 = #DbColumn("","Top5",1);
sessionScope.put("clientsList3",cls3);
var db=session.getCurrentDatabase();
var view7=db.getView("Top5")
var dataa =[] ;
var top =[];
for(var r = 0; r < clientsList3.length; r++){
var Cli = #Trim(#Text(clientsList3[r]));
var VolumeTotal :NotesDocumentCollection = view7.getAllDocumentsByKey(Cli);
var vola = 0;
var array = new Array();
var prod = "";
if (VolumeTotal == 0) {array = 0;}
else{
var doca = VolumeTotal.getFirstDocument();
while (doca != null)
{vola = vola + doca.getItemValueInteger("TotalVolume_Intermediate");
doca = VolumeTotal.getNextDocument(doca);
}
array.push(vola);
}
dataa[r] = array;
dataa.sort(function(a, b) {return b - a;});
top = dataa.slice(0,5);
}
return dataa;
}

You do want to use a managed bean for that, it makes a lot of things much easier. You create a custom class that does the compare operation for you:
public Class TopSeller implements Comparable {
String product;
public String getProduct() {
return this.product;
}
public void setProduct(String product) {
this.product = product;
}
// Add properties as needed
public int compareTo(Topseller theOther) {
// Your ranking code goes here
}
}
In that class your compareTo function does provide the ranking and ordering. Then you just need:
Set<TopSeller> allSeller = new TreeSet<TopSeller>();
... and you are done. The Treeset will provide the ready sorted result and you just bind it to a repeat with 5 rows to display

Related

array to ObjectList angular

import { Board } from './board';
export class Notification {
id : number ;
startDate : Date = null;
endDate : Date = null;
message : string = '';
notificationBoards: Board[] ;
}
Board class
export class Board {
id : number = 0;
name : string = '';
createDate : Date = null;
createdBy : number ;
}
Coponent class is
message.component.ts
///..
submitForm(obj) {
console.log("obj - "+obj);
let notificationObj:Notification = new Notification();
let selectedBoard: Board[];
notificationObj.startDate = obj.startDate;
notificationObj.endDate = obj.endDate;
notificationObj.message = obj.message;
notificationObj.notificationBoards = obj.board;
console.log("notificationObj.notificationBoards"+notificationObj.notificationBoards.length);
for (let i = 0; i < notificationObj.notificationBoards.length; i++) {
console.log(":::"+notificationObj.notificationBoards[i] +":::");
}
...///
I am able to add the notification but unable to add the board obj inside notification object. Board is a list of boards.
obj.board - is an array {10,20,...} which is boardId.
I want to add this array to Board[] and send to service layer.
let selectedBoard: Board[]; is the board list and I want to push notificationObj.notificationBoards[i] to selectedBoard[i] and so on.
Basicaly want to add array to object list Board[].Can someone please help.
Your obj.board is a plain array of numbers (boardIds as you explained), notificationObj.notificationBoards is an array of Board objects.
Typescript would not allow you to convert an object array of type Board class into an array of number values..
You'll have to map one array type to another something like this.
notificationObj.notificationBoards = obj.board.map(boardId=>{
let boardObj:Board = new Board();
boardObj.id = boardId; //since we have only one element (boardId), other fields of board object are not set.
return boardObj;
});
Thanks.

Retrieving only the names from an xml file and putting them into an array in JavaScript

// https://www.w3schools.com/xml/simple.xml
// I am given the above xml file which has menu item names along with other things (price, calories, etc.) and I need to put only the names into an array using JavaScript coding. I'm using repl.it, and I already saved the file as a .xml on the side of my program. I just need to know how to extract only the names into an array. For example, the array should look like: [Belgian Waffles, Strawberry Belgian Waffles, (and so on)].
// In addition, I need to put the calories, the price, and the other stuff in separate arrays but I'm sure if I learn how to make an array for one thing I can do the other arrays too.
// In the past, I made this code to retrieve scores from a file with a list of scores (open repl.it link from the comments to see it in action):
// This program uses a file which has 6 peoples scores to calculate and display the max., min., and ave. scores and also puts them in an array. The program reads the file, trims out the strings so only the numbers are left & converted to numbers, limits the average score to the hundreths place, and verifies the file exists. The number of scores can be changed from 6 and the program would still work.
// Reference(s): https://www.w3schools.com/jsref/jsref_tofixed.asp
// https://codeburst.io/javascript-arrays-finding-the-minimum-maximum-sum-average-values-f02f1b0ce332
// Repl.it link: https://repl.it/live/AFSloyKSNJQjlA
main();
function main() {
var filename = "scores.txt";
if(!fileExists(filename)) {
console.log(`File ${filename} is missing.`)
return
}
var scores = [];
var scores = readFile("scores.txt");
console.log(scores);
var maximum = getMax(scores);
console.log("Maximum score: " + maximum)
var minimum = getMin(scores);
console.log("Mininum score: " + minimum);
var sum = getSum(scores);
var ave = sum / scores.length;
var ave = ave.toFixed(2);
console.log("Average score: " + ave);
}
function fileExists(filename) {
var fs = require('fs');
return fs.existsSync(filename);
}
function readFile(filename) {
var fs = require('fs');
var scores = [];
var contents = fs.readFileSync(filename, 'utf8');
lines = contents.split('\n');
for (var index = 0; index < lines.length; index++) {
var pos = lines[index].indexOf(',') + 1;
var scoreStr = lines[index].substring(pos).trim();
var score = Number(scoreStr);
if (!isNaN(score)) {
scores.push(score);
}
}
return scores;
}
function getMax(scores) {
scores.sort(function(a, b){return b - a});
var maximum = scores[0];
return maximum;
}
function getMin(scores) {
scores.sort(function(a, b){return a - b});
var minimum = scores[0];
return minimum;
}
function getSum(scores) {
return scores.reduce(function(a,b){
return a + b
}, 0);
}
There are two ways you can go about this. If you have a string of the XML you need to run through, and all you need is the contents of a single tag type, you can run that string through this regular expression to get what you need:
// xmlString is a string with the whole XML document in it
const foods = xmlString.match(/(?<=<name>)[A-Za-z ]+(?=<\/name>)/g);
If you want to get it by traversing the XML DOM, you can use JavaScript's standard DOM manipulation tools, like this:
const foodTagList = document.querySelectorAll('food name'); // selects all name nodes under food nodes
const foodList = [];
foodTagList.forEach((el) => foodList.push(el.innerHTML)) // can't use .map because foodTagList isn't an array
console.log(foodList); //prints the list of foods in array form
Finally, if you have the XML in string form and you want to do DOM traversal, you can run it through DOMParser's parseFromString method and then use the instructions for DOM traversal above.

Plotly data from nested for loop

In c# codebehind I define a few Lists this way:
public List<string> divs = new List<string>();
public List<List<string>> names = new List<List<string>>();
public List<List<List<string>>> labels = new List<List<List<string>>>();
public List<List<List<double>>> longitude = new List<List<List<double>>>();
Quite large lists I know but I feel it's necessary for getting all my info from my source organized correctly.
in JS I serialize these like this:
var divArr = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(divs)%>;
var names = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(names)%>;
var lbl = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(labels)%>;
var long = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(longitude)%>;
And then I try to do a function to plot all this on separate graphs. 10 graphs in total on my page that can have several lines on all of them. Trying to make my page as dynamic as possible. So I have a function to loop through all of this and try to plot it all.
function doGraph(){
for(index = 0; index < divArr.length; ++index){
(function() {
var data = [];
for(indx = 0; indx < lbl[index].length; ++indx){
var trace = {
name: names[index][indx],
x: lbl[index][indx],
y: long[index][indx],
mode:'lines'
};
data.push(trace);
}
var gd = document.getElementById(divArr[index]);
plotly.newPlot(gd,data);
})();
}
}
And it ALMOST works. Every graph seems to plot the first set of data given to it but nothing afterwords. Maybe I've been staring at this too long but I just can't see what I'm doing wrong here but I'm sure it's something I've just over looked. Or maybe I'm overreaching and I can't do this sort of thing? Any insight is appreciated!
So I found out the problem was with the serialization from my lists to js arrays. Apparently js serialize can't quite handle the level of multidimensional list I was going crazy with. So I fixed it by making the lists one level less deep and made another list to keep track of how "deep" they are in this fashion:
C# Codebehind:
public List<List<string>> names = new List<List<string>>();
public List<int> numObjs = new List<int>();
public List<List<string>> labels = new List<List<string>>();
public List<List<double>> longitude = new List<List<double>>();
JS Serialization:
var divArr = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(divs)%>;
var names = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(names)%>;
var numO = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(numObjs)%>;
var lbl = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(labels)%>;
var long = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(longitude)%>;
Then the JS function has the real changes with a loop in this way:
function doGraph(){
var cur = 0;
for(var index = 0; index < divArr.length; ++index){
var data = [];
var top = cur + numO[index];
for(var indx = cur; indx < top; ++indx){
data.push({
name: names[indx],
mode:'lines',
x: lbl[indx],
y: long[indx],
});
cur++;
}
var gd = document.getElementById(divArr[index]);
Plotly.newPlot(gd, data,
layout , {scrollZoom:true,modeBarButtonsToRemove:['sendDataToCloud'],showLink:false,displaylogo:false});
}
}
Also my function within a function was definitely unnecessary as #flipperweid said.

How to update Shopping Cart Total properly in Javascript?

I am looking for some Javascript that will:
Update Cart Total on products selected (drop-down menu) and quantities entered
(*Security will be handled by back-end PHP. I have attempted this over the last three days but apparently my code was so bad I feel ashamed to repost it here again)
My Thinking:
- Create a cart object
- Make a function that recalculates the total on any changes that occur
(I can not think of anything else this would require given the javascript will just be passing this over to a PHP script to check anyway)
Does anyone know of some javascript that does the job I seek? Is my thinking correct?
Below is sample shopping cart javascript object built using revealing module pattern.
var shoppingCart = function () {
var obj = {}, items = [];
obj.AddItem = function (itemNo, quantity, price) {
var item = {};
item.itemNo = itemNo;
item.quantity = quantity;
item.price = price;
items.push(item)
};
obj.GetAllItems = function () {
return items;
};
obj.GetItemByNo = function (item) {
for (var i = 0; i < items.length; i++) {
if (items[i].itemNo === item)
return item[i];
}
return null;
};
obj.CalculateTotal = function () {
var total = 0;
for (var i = 0; i < items.length; i++) {
total = total + (items[i].quantity * items[i].price);
}
return total;
};
return obj;
};
var cart = new shoppingCart();
Add items using AddItem method, include additional properties that are useful in the UI.
shoppingcart.AddItem(2,4,2.4);
Gets list of items in the shopping cart
var items = shoppingcart.GetAllItems();
Calculates total price of items in shopping cart
var total = shoppingcart.CalculateTotal();
Please note that I have typed this code in here, so might contain typo's and also I recommend having data type validations for price and quantity as numerics before adding item.

How to create a list in javascript

Javascript can read the list using for loop.
e.g
[WebMethod]
public static List<EmpName> GetData(int startIndex, int maximumRows, string sort, string filter)
{
var emp = objClient.GetData(startIndex, maximumRows, sort, filter);
List<EmpName> lstEmp = new List<EmpName>();
foreach (var item in emp)
{
EmpName objEmp = new EmpName();
objEmp.ID = item.ID;
objEmp.Name = item.Name;
lstEmp.Add(objEmp);
}
return lstEmp;
}
Javascript:
function ReadList(lstEmp)
{
for(var i=0;i<lstEmp.length;i++)
{
alert(lstEmp[i].ID+" "+ lstEmp[i].Name);
}
}
I want to create a list in javascript i.e List to perform various operation at client side how it can be achieved?
There are multiple ways to create a List in JS.
The easiest one being
var l = [];
l[0] = "a";
l[1] = 1;
another way todo so is
var l= [1,"as",func];
refer W3Schools

Categories

Resources