// The function myArray.zip takes N arrays and combines them into one array with all pieces interleaved
// Example: [1,2,3].zip([4,5,6],[7,8,9]) -> [ [1,4,7], [2,5,8], [3,6,9] ]
(function(o){
var zip = function(){
var argLen = arguments.length;
var result = new Array(this.length);
for (var i=this.length-1;i>=0;--i){
var a = result[i] = [this[i]];
for (var j=0;j<argLen;++j) a[j+1] = arguments[j][i];
}
return result;
}
if (Object.defineProperty) Object.defineProperty(o,"zip",{value:zip});
else o.zip = zip;
})(Array.prototype);
var letters = ['a', 'e', 'i', 'o', 'u'];
var values = [12, 22, 7, 7, 3];
var valuesAndLetters = values.zip(letters);
// [[12,"a"],[22,"e"],[7,"i"],[7,"o"],[3,"u"]]
var sorted = valuesAndLetters.sort(function(a,b){
// Sort in descending order, first by value, then by letter
return a[0]<b[0]?1:a[0]>b[0]?-1:a[1]<b[1]?1:a[1]>b[1]?-1:0;
});
// [[22,"e"],[12,"a"],[7,"o"],[7,"i"],[3,"u"]]
Edit: If you don't have (or want to rely on) defineProperty
, and don't want to extend Array.prototype
as a fallback, then here's a version of zip that doesn't touch anyone's prototype:
// Combines N arrays into one array with all pieces interleaved
// e.g. Array.zip([1,2,3],[4,5,6],[7,8,9]) -> [ [1,4,7], [2,5,8], [3,6,9] ]
Array.zip = function zip(a0,a1,etc,aN){
var argLen = arguments.length;
var result = new Array(a0.length);
for (var i=a0..length-1;i>=0;--i){
var a = result[i] = [a0[i]];
for (var j=1;j<argLen;++j) a[j] = arguments[j][i];
}
return result;
};
var letters = ['a', 'e', 'i', 'o', 'u'];
var values = [12, 22, 7, 7, 3];
var valuesAndLetters = Array.zip(values,letters);
// [[12,"a"],[22,"e"],[7,"i"],[7,"o"],[3,"u"]]
var sorted = valuesAndLetters.sort(function(a,b){
// Sort in descending order, first by value, then by letter
return a[0]<b[0]?1:a[0]>b[0]?-1:a[1]<b[1]?1:a[1]>b[1]?-1:0;
});
// [[22,"e"],[12,"a"],[7,"o"],[7,"i"],[3,"u"]]