需求:
一个数组var arr = [4,7,2,9],排序后的新数组var newArr = [2,4,7,9]或者[9,7,4,2]
我们要得到的是排序后元数组的每一项在新数组中的位置所构成的数组:[2,4,7,9]对应[1,2,0,3]/[9,7,4,2]对应[2,1,3,0]
方案一:
1 Array.prototype.getIndex = function () { 2 var orderLength = this.length; 3 var temp, tp; 4 var c = []; 5 for(var l = 0; l < orderLength; l++) { 6 c[l] = l; 7 } 8 for(var u = 0; u < orderLength; u++) { 9 for (var v = 0; v < orderLength-u-1; v++){ 10 if (this[v] > this[v+1]) { 11 temp = this[v]; 12 this[v] = this[v+1]; 13 this[v+1] = temp; 14 tp = c[v]; 15 c[v] = c[v+1]; 16 c[v+1] = tp; 17 } 18 } 19 } 20 return c; 21 //return this; 22 } 23 var arr = [4,7,2,9]; 24 console.log(arr.getIndex());
方案二:
1 var a = [4,7,2,9]; 2 var newArr = []; 3 for (var i = 0, n = a.length; i < n; ++i) { 4 newArr.push({ 5 data: a[i], 6 index: i 7 }) 8 } 9 newArr.sort(function (a, b) { 10 return a.data - b.data; 11 }) 12 var index = []; 13 for (var i = 0, n = newArr.length; i < n; ++i) { 14 index.push(newArr[i].index); 15 } 16 console.log(newA);
本人愚笨只想到这两种解决方案,求更好的方案