Non case-sensitive sorting in dojo dgrid
answer posted by #https://stackoverflow.com/users/237950/ken-franqueiro
grid.on('dgrid-sort', function (event) {
// Cancel the event to prevent dgrid's default behavior which simply
// passes the sort criterion through to the store and updates the UI
event.preventDefault();
// sort is an array as expected by the store API, but dgrid's UI only sorts one field at a time
var sort = event.sort[0];
grid.set('sort', function (a, b) {
var aValue = a[sort.attribute].toLowerCase();
var bValue = b[sort.attribute].toLowerCase();
if (aValue === bValue) {
return 0;
}
var result = aValue > bValue ? 1 : -1;
return result * (sort.descending ? -1 : 1);
});
// Since we're canceling the event, we need to update the UI ourselves;
// the `true` tells it to also update dgrid's internal representation
// of the sort setting, so that toggling between asc/desc will still work
grid.updateSortArrow(event.sort, true);
});
What are the values of a and b variables?
In my case I don't want to touch the library file, my event argument has the complete details of the grid, so I wanted to sort the data present in event argument and update the grid, how should I modify the above code?
jQuery Datatable's sorting order on clicking column header toggles only between asc(Down Arrow) and desc(Up Arrow). i.e.,
1st-click ascending
2nd-click descending
3rd-click asc
4th-click desc
|| ||
|| ||
|| ||
|| ||
odd-click asc
even-click desc.
I want to induce something like this :
1st-click ascending
2nd-click descending
3rd-click no-sorting
4th-click asc
5th-click desc
6th-click no-sort
|| ||
|| ||
|| ||
|| ||
(n%3==1)-click asc
(n%3==2)-click desc
(n%3==0)-click no-sort.
Is there a way to change this behavior in jQuery dataTables? Please help!
Thanks in advance.
Wow, that was interesting. This should do what you need though it's not elegant:
$('#example').on("order.dt", function () {
if(example.settings().order().length === 1){
var order = example.settings().order()[0];
var th = $("#example th:eq(" + order[0] + ")");
if(th.attr("data-sort-next") === "false"){
example.order([]).draw();
th.attr("data-sort-next", true);
}else{
if(order[1] === "desc"){
th.attr("data-sort-next", false);
}else{
th.attr("data-sort-next", true);
}
}
}
});
This working JSFiddle illustrates what's going on. Basically, what you want is available out of the box for multi-column sorting (as noted in the comments). What I've done is intercept the sorting if there's only one column being sorted, without messing up the multi-column sorting. I'll keep on trying to refine it but that should work for you.
when you load a table, it is sorted in a certain way (maybe by id, name or whatever). So what you call 'no-sorting' is, in fact, a 'sort by initial column'.
An easy approach is to let the sorting mechanism as it is, and place a button somewhere to reload the table deleting the current sort. Or even better, make this button sort the table by the initial column.
Solved the issued by maintaining the state of the columns an array, intercepting and stopping the default behavior of the order event and then manually doing :
var dir = 'asc' for ascending
var dir ='desc' for descending
var dir = '' for no-sort
$("#table-id").dataTable.order([colIdx, dir]).draw();
I am implementing Devexpress Grid Control in MVC. I was stuck at a point where i need the current Sorted By column and Sort Order (asc/desc) in javascript. I also tried the clientSide Event OnColumnSortingChanged(s , e) , it is only providing the name of the column at click event not from the gridview javascript object.
Got the answer after research...
Have to add CustomJsProperty to the control in the partial view as below
settings.CustomJSProperties = (s, e) =>
{
var Grid = s as MVCxGridView;
var result = new System.Collections.Hashtable();
foreach (var col in Grid.AllColumns)
{
var dataCol = col as GridViewDataColumn;
if (dataCol != null)
{
if (dataCol.SortIndex == 0)
{
e.Properties["cpColumnsProp"] = new Dictionary<string, object>()
{
{ "sortcolumn", dataCol.FieldName },
{ "sortorder", ((Convert.ToString(dataCol.SortOrder).Equals("Ascending")) ? "asc" : "desc")}
};
}
}
}
};
Handle the ColumnSortingChange event as follows
function gvChartList_OnColumnSortingChanged(s, e) {
$("#hdsortname").val(e.column.fieldName); // contains the sort column name
$("#hdsortorder").val(((s.cpColumnsProp.sortcolumn == e.column.fieldName) ? "desc" : "asc")); // contains the sort column order
}
Last but not the least, One must have to define the default sort index and sort order for the column
settings.Columns.Add(col =>
{
// column details
col.SortIndex = 0;
col.SortAscending();
});
I recently needed similar, where I wanted to save the column order, sort order, and filter information; such that a user could create saved views of a grid, and not have to keep re-entering all these preferences.
I found that in an event CustomJSPropeties I could interact with a sender being an ASPxGridView, such that I could grab a needed value from ASPxGridView.SaveClientLayout(). Also useful here can be the FilterExpression, and the VisibileRowCount - if you want to use the filter expression for exporting, but only when the VisibleRowCount is less than a certain threshold (this is the number of rows shown in the bottom pager area)
settings.CustomJSProperties = (s, e) =>
{
ASPxGridView gridView = (ASPxGridView)s;
e.Properties["cpGridFilterExpression"] = gridView.FilterExpression; //Make Filter Expressions Availabe to JavaScript
e.Properties["cpVisibleRowCount"] = gridView.VisibleRowCount; //Make Visible Row Count Availabe to JavaScript
e.Properties["cpLayout"] = gridView.SaveClientLayout(); //Get Layout String and make it available to JavaScript
};
So what does this do? Properties defined in this event are available as properties of the javascript grid view object. So here we grab these values when we can, and place them in a place where we normally cannot access them.
And then, right from JavaScript we can now access GridView.cpLayout (where GridView is the name/id supplied to your grid.)
<script type="text/javascript">
$(document).ready(function () {
$('#saveButton').click(
function () {
var layout = GridView.cpLayout;
//Perform Save...
}
);
});
</script>
To be clear, this "layout" contains sort order, visible column info, and filter information.
Layout:
https://documentation.devexpress.com/#AspNet/CustomDocument4342
https://documentation.devexpress.com/#AspNet/DevExpressWebASPxGridViewASPxGridView_SaveClientLayouttopic
CustomJSProperties:
https://documentation.devexpress.com/#AspNet/DevExpressWebMvcGridViewSettings_CustomJSPropertiestopic
Note: I add this solution here because this is what I found when I was searching for my issue. As one can see, these are similar topics of accessing the AspxGridView (base of) or MVCGridView within a CustomJSProperties event handler.
I'd like to come up with a good way to have a "suggested" order for how to sort an array in javascript.
So say my first array looks something like this:
['bob','david','steve','darrel','jim']
Now all I care about, is that the sorted results starts out in this order:
['jim','steve','david']
After that, I Want the remaining values to be presented in their original order.
So I would expect the result to be:
['jim','steve','david','bob','darrel']
I have an API that I am communicating with, and I want to present the results important to me in the list at the top. After that, I'd prefer they are just returned in their original order.
If this can be easily accomplished with a javascript framework like jQuery, I'd like to hear about that too. Thanks!
Edit for clarity:
I'd like to assume that the values provided in the array that I want to sort are not guaranteed.
So in the original example, if the provided was:
['bob','steve','darrel','jim']
And I wanted to sort it by:
['jim','steve','david']
Since 'david' isn't in the provided array, I'd like the result to exclude it.
Edit2 for more clarity:
A practical example of what I'm trying to accomplish:
The API will return something looking like:
['Load Average','Memory Usage','Disk Space']
I'd like to present the user with the most important results first, but each of these fields may not always be returned. So I'd like the most important (as determined by the user in some other code), to be displayed first if they are available.
Something like this should work:
var presetOrder = ['jim','steve','david']; // needn't be hardcoded
function sortSpecial(arr) {
var result = [],
i, j;
for (i = 0; i < presetOrder.length; i++)
while (-1 != (j = $.inArray(presetOrder[i], arr)))
result.push(arr.splice(j, 1)[0]);
return result.concat(arr);
}
var sorted = sortSpecial( ['bob','david','steve','darrel','jim'] );
I've allowed for the "special" values appearing more than once in the array being processed, and assumed that duplicates should be kept as long as they're shuffled up to the front in the order defined in presetOrder.
Note: I've used jQuery's $.inArray() rather than Array.indexOf() only because that latter isn't supported by IE until IE9 and you've tagged your question with "jQuery". You could of course use .indexOf() if you don't care about old IE, or if you use a shim.
var important_results = {
// object keys are the important results, values is their order
jim: 1,
steve: 2,
david: 3
};
// results is the orig array from the api
results.sort(function(a,b) {
// If compareFunction(a, b) is less than 0, sort a to a lower index than b.
// See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
var important_a = important_results[a],
important_b = important_results[b],
ret;
if (important_a && !important_b) {ret = -1}
else if (important_b && !important_a) {ret = 1}
else if (important_a && important_b) {ret = important_a - important_b}
else {ret = 0}; // keep original order if neither a or b is important
return(ret);
}
)
Use a sorting function that treats the previously known important results specially--sorts them to the head of the results if present in results.
items in important_results don't have to be in the results
Here's a simple test page:
<html>
<head>
<script language="javascript">
function test()
{
var items = ['bob', 'david', 'steve', 'darrel', 'jim'];
items.sort(function(a,b)
{
var map = {'jim':-3,'steve':-2,'david':-1};
return map[a] - map[b];
});
alert(items.join(','));
}
</script>
</head>
<body>
<button onclick="javascript:test()">Click Me</button>
</body>
</html>
It works in most browsers because javascript typically uses what is called a stable sort algorithm, the defining feature of which is that it preserves the original order of equivalent items. However, I know there have been exceptions. You guarantee stability by using the array index of each remaining item as it's a1/b1 value.
http://tinysort.sjeiti.com/
I think this might help. The $('#yrDiv').tsort({place:'start'}); will add your important list in the start.
You can also sort using this function the way you like.
Live demo ( jsfiddle seems to be down)
http://jsbin.com/eteniz/edit#javascript,html
var priorities=['jim','steve','david'];
var liveData=['bob','david','steve','darrel','jim'];
var output=[],temp=[];
for ( i=0; i<liveData.length; i++){
if( $.inArray( liveData[i], priorities) ==-1){
output.push( liveData[i]);
}else{
temp.push( liveData[i]);
}
}
var temp2=$.grep( priorities, function(name,i){
return $.inArray( name, temp) >-1;
});
output=$.merge( temp2, output);
there can be another way of sorting on order base, also values can be objects to work with
const inputs = ["bob", "david", "steve", "darrel", "jim"].map((val) => ({
val,
}));
const order = ["jim", "steve", "david"];
const vMap = new Map(inputs.map((v) => [v.val, v]));
const sorted = [];
order.forEach((o) => {
if (vMap.has(o)) {
sorted.push(vMap.get(o));
vMap.delete(o);
}
});
const result = sorted.concat(Array.from(vMap.values()));
const plainResult = result.map(({ val }) => val);
Have you considered using Underscore.js? It contains several utilities for manipulating lists like this.
In your case, you could:
Filter the results you want using filter() and store them in a collection.
var priorities = _.filter(['bob','david','steve','darrel','jim'],
function(pName){
if (pName == 'jim' || pName == 'steve' || pName == 'david') return true;
});
Get a copy of the other results using without()
var leftovers = _.without(['bob','david','steve','darrel','jim'], 'jim', 'steve', 'david');
Union the arrays from the previous steps using union()
var finalList = _.union(priorities, leftovers);
Good day stack people,
I'm doing research for my self on how to combine two Json feeds in one and display them in one timeline by date using JS or jQuery.
For example we will have two json files file1.json and file2.json (one from twitter and another from filckr).
I need "n" numbers of latest items and show append them to show by items time.
Any ideas or hints?
Thank you!
P.S. Example feeds: http://twitter.com/status/user_timeline/ignaty.json?count=5 and http://api.flickr.com/services/feeds/groups_pool.gne?%20id=675729#N22&lang=en-us&format=json
Lets pick only any one value from each.
Here's some method that should do that (you need to tweak it though).
Essentially you request the two APIs and then (once both requests are completed) you sort an array of normalized objects.
var all = [];
var waiting = 2; // number of services you request
// once you get response1 or response2
function parseFlickr(data) {
$.each(data, function(index, item) {
// normalize item here depending on service format (parse date)
var normalized = {};
normalized.date = new Date(Date.parse(item.date));
all.push(normalized);
});
if(--waiting == 0) { onDone(); }
}
function onDone() {
all.sort(function(a,b) {
// switch -1 and +1 to invert ordering
return (a.date < b.date ? -1 : (a.date > b.date ? +1 : 0));
});
// do the rendering/appending (you might limit the amount here)
}