How to create a list in javascript - 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

Related

Count in an Array a number of same value Items in Razor , Umbraco

i am having an array of records
Model.Categories = ["apple", "banana", "apple", "orange"]
from this array i am displaying the records one by one
#foreach (var category in Model.Categories)
{
#category
}
so this currently displaying two times apple record but i wants to display single time with the count beside like this
apple -(2)
banana
orange
like this can any help me with this on Razor how to implement this ?
To do this, we need to create Method in Model which will return a Dictionary of category and its occurrence. Please find the below method which can be used to return the dictionary.
public Dictionary<string,int> CountArray()
{
Dictionary<string, int> countArr = new Dictionary<string, int>();
foreach (var category in Categories)
{
if(countArr.ContainsKey(category))
{
countArr[category] = countArr[category] + 1;
}
else
{
countArr[category] = 1;
}
}
return countArr;
}
Now create a variable in cshtml file and assign this value returning from model.
Use this variable in foreach loop.
I guess this will help you in resolving your problem.
I really don't suggest this approach. But as you need help please find the Razor Code.
#{ Dictionary<string, int> countarry = new Dictionary<string, int>();}
#foreach (var category in Model.Categories)
{
if (countarry.ContainsKey(category))
{
countarry[category] = countarry[category] + 1;
}
else
{
countarry[category] = 1;
}
}
#foreach (var categoryName in countarry.Keys)
{
if(countarry[categoryName] > 1)
#categoryName - (#countarry[categoryName])
else
#categoryName
}
I hope this is what you are expecting.
I have simple solution
var fruits = ["apple","coconut","apple","banana","papaya"];
var sortFruits = [];
for(fruit of fruits ){
if(sortFruits.includes(fruit)==false){
sortFruits.push(fruit);
}
}
console.log(sortFruits);
Not sure if it could be "Razor code" as you call, but why don't you use Linq GroupBy?
The following code produce your expected output on browser.
#foreach (var category in categories.GroupBy(k => k))
{
<a>#category.Key#(category.Count() > 1 ? $" - ({category.Count()})" : "")</a><br/>
}
Example above works in Razor 3.0.0.0 and .Net franework 4.6.1 (C# 6.0)
The code above is a result after trying to output as expected in the question. If making it simpler, possibly it could work in earlier versions.
#foreach (var category in categories.GroupBy(k => k))
{
<a>#category.Key - #category.Count()</a><br/>
}

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.

Call a list in code behind of ASPX , in javascript code in foreach loop?

I have the following aspx.cs :
public partial class BarChart
{
public class LabelsDetail
{
public string LabelId { get;set; }
public string LabelDesc { get; set; }
}
public List<LabelsDetail> LabelsDetails { get; set; }
public void InsertDataToLabelsDetails()
{
// Data comes from somewhere into "LabelsDetails"
}
}
and the following JS code in the ASPX page :
function setupBarChart(JQObjectContainer, JsonData) {
var hashTableSize = <%=this.LabelsDetails.Count%>;
var hashtable = {};
if (hashTableSize != 'undefined' && hashTableSize > 0)
{
for (var item in <%=this.LabelsDetails%>)
{
hashtable[item.LabelId] = item.LabelDesc;
}
}
}
How can I do a foreach on a server side list in the client side ?
At the moment I get Uncaught SyntaxError: Unterminated template literal
When I try to loop on the server side list (this.LabelsDetails) .
Thanks
Try This
function setupBarChart(JQObjectContainer, JsonData) {
var hashTableSize = <%=this.LabelsDetails.Count%>;
var hashtable = {};
var json = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.LabelsDetails)%>;
if (hashTableSize != 'undefined' && hashTableSize > 0)
{
for (var key in json)
{
hashtable[json[key].LabelId] = json[key].LabelDesc;
}
}
}
You must convert your collection to a notation that JavaScript will understand, to do that you can use JavaScriptSerializer or any other JSON converter:
var collection = new[]{
new { Name = "a" },
new { Name = "b" },
new { Name = "c" },
new { Name = "d" }
};
System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
Console.WriteLine(s.Serialize(collection));
This will output [{"Name":"a"},{"Name":"b"},{"Name":"c"},{"Name":"d"}] whhich is a valid array notation for JavaScript. You also can improve the way you iterate in JS:
var array = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(this.LabelsDetails)%>;
for(var x=0;x<array.length;x++)
{
hashtable[array[x].LabelId] = array[x].LabelDesc;
}
For...In is not good to iterate arrays in JS, it's not the same as foreach in C#.
From MDN:
Array iteration and for...in
Note: for..in should not be used to iterate over an Array where the
index order is important. Array indexes are just enumerable properties
with integer names and are otherwise identical to general Object
properties. There is no guarantee that for...in will return the
indexes in any particular order and it will return all enumerable
properties, including those with non–integer names and those that are
inherited.
However, it might be worth to review your approach and use other technologies to do the connection between client-side and server-side.

Sort document collection by values total in xpages

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

Unable to read a list in Jquery

I am trying to read (access values) a list in Jquery like this:
var list = { length: 0 };
var subTypeId = "";
list = '<%: Model.lstDC_TAn %>';
alert('list = ' + list);
for (var j = 0; j < list.length; j++) {
subTypeId = list[j].DCSubTypeId;
alert('subTypeId = ' + subTypeId)
The alert for list shows that its a "Generic list", however, the subTypeId is always undefined. I have checked in the controller. The list is not null and the property that I am trying to access (DCSubTypeId) is also present inside each element in the list.
EDIT:
public List<DC_TAn> lstDC_TAn { get; set; }
Your logic is flawed. As it stands, you're dealing with raw string. Such code:
list = 'Generic list';
alert(list[0]);
Will alert "G", as string is array of characters. Character/String in JavaScript indeed has no property called "DewCardSubTypeId".
You need to first change the server side code to output proper object, e.g.
public string lstDewCard_TypeAssociation
{
get
{
return "[{\"DewCardSubTypeId\": 5}, {\"DewCardSubTypeId\": 100}]";
}
}
Then get rid of the quotes when assigning it:
list = <%: Model.lstDewCard_TypeAssociation %>;
Then your code should work.

Categories

Resources