javascript broken syntax - javascript

Alright, I or someone I work with broke the syntax here somewhere, and I'm not sure where, as the debugger is giving me some random garble as the error. Anyway here is the function, I think I'm missing a bracket somewhere, but this is just evading me for some reason.
var sort_by = function(field, reverse, primer) {
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ((A < B) ? -1 : (A > B) ? +1 : 0)) * [-1,1][+!!reverse];
}
}

there's an extra closing parenthesis on the line
return ((A < B) ? -1 : (A > B) ? +1 : 0))
should be
return ((A < B) ? -1 : (A > B) ? +1 : 0) ...etc

It would be useful if could provide the debugger error anyway. I exectued it in Chrome Developer Console and it gave the error:
SyntaxError: Unexpected token )
Which made it easy to find this broken line:
return ((A < B) ? -1 : (A > B) ? +1 : 0)) * [-1,1][+!!reverse];
You have unbalanced parenthesis. It should be:
return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1,1][+!!reverse];

There's one extra closing bracket here. Remove it.
return ((A < B) ? -1 : (A > B) ? +1 : 0)) * [-1,1][+!!reverse];
Also, semicolon everything.
var sort_by = function(field, reverse, primer) {
var key = function(x) {
return primer ? primer(x[field]) : x[field];
};
return function(a, b) {
var A = key(a), B = key(b);
return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1, 1][+!!reverse];
};
};

Related

Sort by Status then by date JavaScript

I have an array of the following type I wan to sort. I want to sort them by the status and show false ones first and and then sort them by their date. I don't know if I should use group by then sort.
"itemlist": [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}]
I have used the below code it sorts the array by status but the date sorting is not working. can someone help me with a better method and what am I doing wrong ? , Thanks
var res=itemlist.sort((a, b) => (a.Status === b.Status ) ? 0 : a.Status ? 1 : -1 || b.Date- a.Date);
The reason is that your date is string format,not actually date,you need to change it to date when compare
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date));
also,you expression is too complex to read and debug,had better to use () to wrap it or use if else condition instead
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));
working code
var itemlist = [{
"Status":false,"Date":"2021-07-23T07:43:01.377Z","Title":"test4"},{
"Status":false,"Date":"2021-07-23T07:28:23.841Z","Title":"test3"},{
"Status":false,"Date":"2021-07-23T07:03:12.736Z","Title":"test2"},{
"Status":false,"Date":"2021-07-23T07:02:01.901Z","Title":"test1"},{
"Status":false,"Date":"2021-07-23T06:46:34.614Z","Title":"test1"},{
"Status":false,"Date":"2021-07-22T14:33:41.351Z","Title":"test0"},{
"Status":true,"Date":"2021-07-16T06:28:41.568Z","Title":"Test"}];
var res=itemlist.sort(
(a, b) => (a.Status === b.Status ) ?
0 : (a.Status ? 1 : -1 || new Date(b.Date)- new Date(a.Date)));
//output the sorted result
console.log(res);

Ternary Operator - 3 conditions

I'd like to rewrite this with a ternary operator. I believe I need 2 operators.
if (a.quantity > b.quantity) {
return -1;
} else if (a.quantity < b.quantity) {
return 1;
} else {
return 0;
}
Ternary
return (a.quantity > b.quantity) ? -1 : (a.quantity < b.quantity) ? 1 : 0;
would this be the equivalent?
If you need the value for sorting, you could take the delta of the two values:
data.sort((a, b) => a.quantity - b.quantity); // ascending
data.sort((a, b) => b.quantity - a.quantity); // descending
Yes those are equivalent
return (a.quantity > b.quantity) ? -1 : (a.quantity < b.quantity) ? 1 : 0;

Additional parameter in custom sort function in Javascript

I was looking at some custom sort function in Javascript & am trying to understand how it really works. Below is the code;
sortArrayBy: function(a, b, param) {
if (a[sortKey] < b[sortKey]) {
return isAscending ? -1 : 1;
}
if (a[sortKey] > b[sortKey]) {
return isAscending ? 1 : -1;
}
return 0;
}
var self = this;
var sortFunc = function(a, b) {
return self.sortArrayBy(a, b, self.get('sortKey')); // What is the last param used for here ?
};
myArr.sort(sortFunc, key); // What is 'key' used for here ?
My question is in 'sortFunc' defintion, what is the last parameter self.get('sortKey') used for & What is 'key' used for in myArr.sort(sortFunc, key)?

javascript conflict with prototype js

I have following piece of code and this has started breaking after i included Prototype.js into the page.
function JsonArrayByProperty(objArray, prop, direction) {
if (arguments.length < 2) throw new Error("sortJsonArrayByProp requires 2 arguments");
var direct = arguments.length > 2 ? arguments[2] : 1; //Default to ascending
if (objArray && objArray.constructor === Array) {
var propPath = (prop.constructor === Array) ? prop : prop.split(".");
objArray.sort(function (a, b) {
for (var p in propPath) {
if (a[propPath[p]] && b[propPath[p]]) {
a = a[propPath[p]];
b = b[propPath[p]];
}
}
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
return ((a < b) ? -1 * direct : ((a > b) ? 1 * direct : 0));
});
}
}
It breaks at following lines with error
Uncaught TypeError: Object #<Object> has no method 'match'
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
Your problem most likely starts on this line:
for (var p in propPath) {
Once you add prototype.js to your page, you cannot use the common (but incorrect) shortcut of iterating over an array using for(foo in bar). That's because array elements are no longer simple strings or floats, they are full-fledged "extended" objects that happen to evaluate back to strings or floats if you iterate over them correctly.
for(var i = 0; i < propPath.length; i++) {
will get you back on track.

javascript sort array

My array isn't being sorted properly. Can someone let me know what I am doing wrong?
...
sortArray = new Array ("hello", "Link to Google", "zFile", "aFile");
//sort array
if (dir == "asc") {
sortArray.sort(function(a,b){return a - b});
} else {
sortArray.sort(function(a,b){return b - a});
}
for(var i=0; i<sortArray.length; i++) {
console.log(sortArray[i]);
}
the log is showing them in the same order as they were entered.
You want to make a comparison in your sort, not a subtraction:
if (dir == "asc") {
sortArray.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return a === b ? 0 : a > b : 1 : -1;
});
} else {
sortArray.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
return b === a ? 0 : b > a : 1 : -1;
});
}
I also used toLowerCase() so that 'Link to Google' is placed appropriately.
EDIT: Updated to fix comparison issue according to comment.
See example →
You're trying to sort by subtracting strings, to which you'll get NaN.
The trouble is that "a - b" is treating the strings like numbers, which returns NaN. You will get the behavior you are looking for (assuming you are looking for case-sensitive sorts) if you replace your sorts with:
if (dir == "asc") {
sortArray.sort(function(a,b){return a < b ? -1 : 1});
} else {
sortArray.sort(function(a,b){return b < a ? -1 : 1});
}
Your comparator functions returns NaN, since it receives two strings, and performs subtraction, an operation that isn't well-defined on strings.
What you should have is something more like:
function(a,b){
return a>b? 1 : (a<b ? -1 : 0);
}
or you can use localeCompare:
function(a,b){
return a.localeCompare(b);
}
Remember to treat case appropriately, e.g. "L" < "a" whilst "l" > "a"

Categories

Resources