In both cases, $.each
is just being used to loop through the array entries in tmp
.
This answer has an exhaustive list of your options for looping through array entries in JavaScript without using any libraries. With current browsers, the usual way would be Array#forEach
:
tmp.forEach(function(value, index) {
// ...
});
Note that the arguments to the callback are in a different order. But again, other options are listed in that other answer. In fact, when using forEach
, we don't need the index
arugment, as the code in your $.each
loops isn't using it, it's just there because it's the first argument and the code wants the second (value
). So we can leave it off:
tmp.forEach(function(value) {
// ...
});
In each place $.each
was used in your original code, if you just drop the body of the $.each
call into the above where I have // ...
, it will do the same thing $.each
was doing.
So for the first call (in the === '[object Array]'
branch), that looks like this:
tmp.forEach(function(value){
aSorted.push(value.value);
});
For the second call (in the === '[object Object]'
branch), that looks like this:
tmp.forEach(function(value) {
oSorted[value.key]=value.value;
});
While the above would be sufficient to get rid of $.each
, here's a completely rewritten version with explanatory text:
ArraySort = function(array, sortFunc){
// If `array` is an array, this is trivial: Copy it and use `Array#sort`
// (since the original created a copy)
if (Array.isArray(array)) {
return array.slice().sort(sortFunc);
}
// If `array` is not a plain object, return `undefined`
// (This is effectively what the original did, by simply
// falling off the bottom of the function.)
if (object.prototype.toString.call(array) !== "[object Object]") {
return undefined;
}
// Create a "sorted" version of the object.
// NOTE!!! In the current version of JavaScript, object properties HAVE
// NO ORDER. At all. None. However, in the next version of JavaScript,
// ECMAScript6 (aka "ES6"), they will have an order, and V8 (the engine
// in NodeJS) already supports that order. The order is based on the
// order in which the properties were created (but it's more complicated
// that that, see:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys
// Get an array of objects with `key` being the property name and
// `value` being its value.
var tmp = Object.keys(array).map(function(key) {
return {key: key, value: array[key]};
});
// Sort `tmp` according to `sortFunc` on its values
tmp.sort(function(o1, o2) {
return sortFunc(o1.value, o2.value);
});
// Create and return a new object with the properties in that order (see
// caveat above!!)
var result = {};
tmp.forEach(function(entry) {
result[entry.key] = entry.value;
});
return result;
};
Here's that link about property order: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys