Dustjs Display Unique Values Only? - dust.js

Lets say i have the following JSON
{
names: ["John", "Peter", "Ron", "John", "James", "John"]
}
I need DustJS to render the following names
John
Peter
Ron
James
Notice that these are unique values in an array. Any ideas? Thank you so much!

This can be done using a common algorithm to 'unique' an array:
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
It's done by taking the values, attempting to add them as keys to an object (which will only work if they're different). If success, it adds that key to an array. If fail, it ignores the key. It then returns the array. I have a working dust.js demo here:
Working Demo

I believe this will generate your "also acceptable" form:
{#options}] {.} {#variants} {.options[$idx]} {/variants} {/options}

Related

Get every n number of elements in list Flutter Dart

I have a list of elements and I need to get a list containing the first element followed by every nth element afterwards. For example: given n = 3 and the list [banana, cherry, apple, pear, kiwi], I need to get the list [banana, pear]. I need this regardless of specific content, since the list depends on user input.
How do I do this using Dart?
You may access list in dart by providing an index like for example:
List<String> fruits = ["banana","cherry","apple","pear","kiwi"];
print(fruits[0]); // Will print to the console "banana";
On your case, you are trying to access index 0 and index 3 which is "banana" and "pear".
You may create a function that accepts an index like:
String getFruit(int index, List<String> fruits) => fruits[index];
print(getFruit[0]); // Will print "banana";
or if you need to actually get the specific ranges you may use:
List<String> fruits =["banana","cherry","apple","pear","kiwi"].getRange(0,4);
// Will give you "banana","cherry","apple","pear
You may check : https://api.dart.dev/be/180791/dart-core/List-class.html for more information.
Edited answer based off the comment:
List<String> getElements(List userInput, nIndex){
List elements = [];
for(int x = 0; x<userInput.length;x++){
if(x % nIndex == 0){
elements.add(userInput[x]);
}
}
return elements;
}
List fruits = ["banana","cherry","apple","pear","kiwi"];
print(getElements(fruits,2));
or you may try to look and use List.retainWhere() depending on your use case.
Dart has a great set of collection operators that make this type of problem pretty straightforward to solve. For example, we could do something like:
extension X<T> on List<T> {
List<T> everyNth(int n) => [for (var i = 0; i < this.length; i += n) this[i]];
}
main() {
final fruit = ["banana", "cherry", "apple", "pear", "kiwi"];
print(fruit.everyNth(3));
}
Output:
[banana, pear]
You can use this extension method, which will work on lists of any type:
extension GetEveryN<T> on List<T> {
List<T> elementsEveryN(int n) {
List<T> result = [];
for(int index = 0; index < length; index +=1) {
if(index % n == 0) {
result.add(this[index]);
}
}
return result;
}
}
Trying it in an example:
List<String> list = ["banana", "cherry","apple", "pear","kiwi"];
print(list.elementsEveryN(2)); // [banana, pear]

Request.Cookie - Cookie is not sent or not excepted

I'm developing a shopping cart function.
I need product data from the server that used to render the shopping cart page.
Every time the Add-to-cart button is hit, I stringify this array ( using JSON.stringify() ):
var CART = [{productId: 102, quantity: 3} , {productId: 211, quantity: 6}];
I want to get this data using Request.Cookie["shoppingCart"] in my ASP.NET application,
but when I debug It is always null
This is what the browser return when I call document.cookie
"shoppingCart=[{\"productId\":101617121,\"quantity\":2}]"
But when I try to change the value of the cookie to something like: shoppingCart=testresult ,
the Request.Cookie["shoppingCart"] then has value.
Thank you in advance for helping me!
I solved it.
First, I tried to remove some special chars which are: " and , .
And Request.Cookie then had values. So it seems like ASP.NET just doesn't except these characters in cookie value. ( Tell me if I'm wrong please )
My solution was instead of convert JSON string, I used this formular for each product in the shopping cart : var item = `{productId}:{quantity}`; .
For example:
var sampleCookie = "11231:16:15121:8";
Split the string with : char then use a simple code to get the data.
My code for this:
string cookie = Request.Cookies["shoppingCart"];
var cartItems = new List<CartItem>();
if (cookie != null && cookie.Length > 0)
{
string[] values;
values = cookie.Split(':');
int i = 0;
while (i < values.Length)
{
cartItems.Add(new CartItem()
{
ProductId = values[i],
Quantity = Convert.ToInt32(values[i+1])
});
i += 2;
}
}

Is it possible for a script to reference a line on a new record?

This relates to some older questions on SuiteScript 1.0. I've got a 2.0 script that has to be 2.0, so I can't use the old nlapiGetLineItemValue - it has to be Record.getSublistValue(options). But I need it to get the line value on a new, unsaved record BeforeSubmit.
It keeps returning "getSublistValue" is not defined in object, and checking NetSuite Field Explorer confirms that the unsaved record has no defined lines.
The same applies to AfterSubmit.
So is there any work around, or is it even possible, to reference the line item value when the record is being created?
ADDING SOME CODE, WHERE THE QUESTION APPLIES:
var recNew = context.newRecord
var ItemID = recNew.getSublistValue({
sublistId: 'items',
fieldId: 'itemid',
});
var listIDs = ["6646", "17745", "17945", "21349"];
var a_filters = [];
a_filters.push(new nlobjSearchFilter(ItemID, null, 'anyof', listIDs));
{
// an action
}
getSublistValue requires you to pass the line number.
var recNew = context.newRecord
for (var x =0; x< recNew.getLineCount({sublistId:'item'}); x++) {
var ItemID = recNew.getSublistValue({ sublistId: 'item', fieldId: 'item', line: x });
// DO STUFF
}
try using
if(scriptContext.type == 'edit'){
var recNew = scriptContext.newRecord
recNew.getSublistValue(options)
}

Highcharts error 14 in chart from HTML table

I'm using the highcharts data module to build a chart from an html table. In the data configuration of the chart I just have:
data: {
table: table
}
But if I have string values such as "null", "NA", or even comma separators in the HTML table I get highcharts error 14, 'string value passed to chart...'
What I've tried:
Since HC should be able to handle null values I replaced NA will null in the tables. I also tried just leaving the blanks "" blank. But the issue is with the thousand separators. So I added thousandsSep: ',' hoping the chart output would understand that commas are part of the display but that doesn't work.
My next thought was to use a formatter function:
data: {
table: function(){...change strings to float etc}
}
None of my attempts at the latter seem to work as I can't figure out what the data object looks like when accessed from a table. Any advice would be appreciated.
A solution that seems to have fixed the issue was to add a "parsed" function here is the api reference: http://api.highcharts.com/highcharts/data.parsed
I added the following to the data property:
data: {
table: 'datatable',
parsed: function()
{
var chartData = this.columns;
var nData = [];
for(var a in chartData)
{
var tempArray = [];
for(var e in chartData[a])
{
var v = chartData[a][e].replace(/\,/g,"").replace("NA","0");
/\d/g.test(v) == true ? v = parseFloat(v) : v = v;
tempArray.push(v);
}
nData.push(tempArray);
}
this.columns = nData;
//alert(JSON.stringify(nData));
//this.columns = [];
//this.columns.push(nData[0]);
//this.columns.push(nData[1]);
}
},
...etc

Delete from array with reindex - AS3.0

I would like to delete a item from my array and still have the same index for every item afterwards.
Example
var arr:Array = new Array();
arr[1] = 'One';
arr[2] = 'Two';
arr[3] = 'Three';
arr.splice(2, 1);
for(var index in arr) {
trace(index+':'+arr[index]);
}
Outputs:
1:One
2:Three
And should ouput
1:One
3:Three
Anyone that could help me a little bit here? :-)
If you splice an element from an array then the array is refreshed and the elements after that index is moved to fill that index.
If you really want to have the elements in the same index always then do assign the index with empty string instead of splicing it.
Try this:
array[1] = "";
instead of,
array.splice(1, 1);
According to me splicing is a good way of practicing.
You can use delete operator:
var arr:Array = new Array();
arr[1] = 'One';
arr[2] = 'Two';
arr[3] = 'Three';
delete arr[2];
for(var index in arr) {
trace(index+':'+arr[index]);
}
I found a solution to my problem.
Instead of using a array, i'll use a object to hold my items. Like this
var objArr = {1: 'One', 2: 'Two', 3: 'Three'};
And when I delete i do like this.
delete objArr[1];
I know I wont get the array functions then. But in my case I don't need them.

Resources