javascript conflict with prototype js - javascript

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.

Related

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)?

How can one compare string and numeric values (respecting negative values, with null always last)?

I'm trying to sort an array of values that can be a mixture of numeric or string values (e.g. [10,"20",null,"1","bar","-2",-3,null,5,"foo"]). How can I sort this array such that
null values are always placed last (regardless of sorting order, see jsFiddle)
negative numbers are sorted correctly (i.e. they are less than positive numbers and sort correctly amongst themselves)
? I made a jsFiddle with detailed numeric and string examples (using localeCompare and the numeric option), but will paste the numeric version of my sorting algorithm below as a starting point.
// Sorting order
var order = "asc"; // Try switching between "asc" and "dsc"
// Dummy arrays
var numericArr = [10,20,null,1,-2,-3,null,5];
// Sort arrays
$(".output1").append(numericArr.toString());
numericArr.sort(sortByDataNumeric);
$(".output2").append(numericArr.toString());
// Numeric sorting function
function sortByDataNumeric(a, b, _order) {
// Replace internal parameters if not used
if (_order == null) _order = order;
// If values are null, place them at the end
var dflt = (_order == "asc" ? Number.MAX_VALUE : -Number.MAX_VALUE);
// Numeric values
var aVal = (a == null ? dflt : a);
var bVal = (b == null ? dflt : b);
return _order == "asc" ? (aVal - bVal) : (bVal - aVal);
}
The problem with my string sorting algorithm (see jsFiddle) is that I can't find a way to always place null values last and negative values aren't correctly sorted within themselves (e.g. -3 should be less than -2)
Edit
To answer the comments, I expect [10,"20",null,"1","bar","-2",-3,null,5,"foo"] to sort to [-3,"-2","1",5,10,"20","bar","foo",null,null]
You should first check to see if either value is null and return the opposite value.
On a side note:
For your default _order value, you should check if the parameter is undefined instead of comparing its value to null. If you try to compare something that is undefined directly you will get a reference error:
(undefinedVar == null) // ReferenceError: undefinedVar is not defined
Instead, you should check if the variable is undefined:
(typeof undefinedVar == "undefined") // true
Also, it's probably a better idea to wrap your compare function in a closure instead of relying on a global order variable.
Sometime like:
[].sort(function(a, b){ return sort(a, b, order)})
This way you can sort at a per-instance level.
http://jsfiddle.net/gxFGN/10/
JavaScript
function sort(a, b, asc) {
var result;
/* Default ascending order */
if (typeof asc == "undefined") asc = true;
if (a === null) return 1;
if (b === null) return -1;
if (a === null && b === null) return 0;
result = a - b;
if (isNaN(result)) {
return (asc) ? a.toString().localeCompare(b) : b.toString().localeCompare(a);
}
else {
return (asc) ? result : -result;
}
}
function sortByDataString(a, b) {
if (a === null) {
return 1;
}
if (b === null) {
return -1;
}
if (isNumber(a) && isNumber(b)) {
if (parseInt(a,10) === parseInt(b,10)) {
return 0;
}
return parseInt(a,10) > parseInt(b,10) ? 1 : -1;
}
if (isNumber(a)) {
return -1;
}
if (isNumber(b)) {
return 1;
}
if (a === b) {
return 0;
}
return a > b ? 1 : -1;
}
fiddle here: http://jsfiddle.net/gxFGN/6/
I left out the order parameter, but you could always reverse the array at the end if needed.
Use this:
function typeOrder(x) {
if (x == null)
return 2;
if (isNaN(+x))
return 1;
return 0;
}
function sortNumber(a, b) {
a = parseInt(a, 10); b = parseInt(b, 10);
if (isNaN(a) || isNaN(b))
return 0;
return a - b;
}
function sortString(a, b) {
if (typeof a != "string" || typeof b != "string")
return 0;
return +(a > b) || -(b > a);
}
order = order == "dsc" ? -1 : 1;
numericArr.sort(function(a, b) {
return order * ( typeOrder(a)-typeOrder(b)
|| sortNumber(a, b)
|| sortString(a, b)
);
});
(updated fiddle)
I'm pretty sure that your problem is a red herring... the abstract function that you past into sort doesn't get a third parameter (in your case _order). So in your situation that's always going to be undefined.
Please reconsider your code with that in mind and see what you get.
The array you specify is entirely Numeric so your sort should work correctly, though as other commenters have suggested, if your array ever winds up with string values (i.e. "10", "-7" etc) you'll want to parseInt and test for isNaN before doing your comparison.

javascript broken syntax

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];
};
};

sort objects by a property values

I have some objects in an array and want to have them sorted. The objects should be sorted by a metric value. So I have the following function:
objectz.sort(function(a,b){
return b.metric - a.metric;
}
The problem is that some objects have the same property values and the results of the sorting are always different.I want to additionally sort the objects with the same metric value by their name property so I get the same order of objects every time I sort them.
Thx in advance!
objectz.sort(function(a,b){
var result = b.metric - a.metric;
if (!result) return a.name > b.name ? 1 : -1;
return result;
});
Similar to zerkms:
objectz.sort(function(a,b) {
var x = b.metric - a.metric;
return x || b.name - a.name;
});
Seems to be a reverse sort (higher values occur first), is that what you want?
Edit
Note that the - operator is only suitable if the value of 'name' can be converted to a number. Otherwise, use < or >. The sort function should deal with a.name == b.name, which the > opertator on its own won't do, so you need something like:
objectz.sort(function(a,b) {
var x = b.metric - a.metric;
// If b.metric == a.metric
if (!x) {
if (b.name == a.name) {
x = 0;
else if (b.name < a.name) {
x = 1;
else {
x = -1;
}
}
return x;
});
which can be made more concise:
objectz.sort(function(a,b) {
var x = b.metric - a.metric;
if (!x) {
x = (b.name == a.name)? 0 : (b.name < a.name)? 1 : -1;
}
return x;
});
Given that the metric comparison seems to be largest to smallest order, then the ternary exrpession should be:
x = (b.name == a.name)? 0 : (b.name < a.name)? -1 : 1;
if it is required that say Zelda comes before Ann. Also, the value of name should be reduced to all lower case (or all upper case), otherwise 'zelda' and 'Ann' will be sorted in the opposite order to 'Zelda' and 'ann'

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