开发者

Javascript sorting string array based on int array

开发者 https://www.devze.com 2023-03-04 06:38 出处:网络
In javascript, I have an array: letterArray [\'a\', \'e\', \'i\', \'o\', \'u\'] corresponding to that array, I have another array:

In javascript, I have an array:

letterArray ['a', 'e', 'i', 'o', 'u']

corresponding to that array, I have another array:

valueArray [12, 22, 7, 7, 3]

I want to sort the valueArray into

[22, 1开发者_如何学运维2, 7, 7, 3]

but the letterArray also needs to be sorted the same way:

['e', 'a', 'i', 'o', 'u']

How would I be able to do this?


You can do this using zipping method. I would use _.zip.

// [["a", 12], ["e", 22], ...]
var arr = _.zip(letterArray, valueArray); // zip them up.
// sort
// [["u", 3], ["i", 7] OR ["o", 7], ...]
var sortedArr = _.sortBy(arr, function(val) {
    // sort by the value array.
    return val[1];
});
// pluck the letter array back out
// ["u", "i" OR "o", ...]
var newLetterArray = _.pluck(sortedArr, "0");
// pluck the value array back out
// [3, 7, 7, ...]
var newValueArray = _.pluck(sortedArr, "1");

I'm afraid your example is complicated by having duplicate numbers which means you can not garantuee order on sorting. This is browser specific whether "i" or "o" comes first.


Method 1: Zip up your two arrays into a zipped-up-thing, like [[12,'a'], [22, 'e'], [7, 'i'], [7, 'o'], [3, 'u']] and then sort the resulting array. Then just read off the letters. This has the advantage that you can use a built-in sorting algorithm, and you just have to write the accessor.

Method 2: Roll your own sorting algorithm, and every time you do an operation that changes the int array, do the corresponding operation on the letter array.

I recommend method 1.


// myArray.zip interleaves N arrays into one array of all pieces
// e.g. [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:

// Interleaves N arrays into one array of all pieces
// 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"]]


function odd_way_to_sort(intArr, charArr){
    var min = intArr[0]
    for(index in intArr){
        //some sort of sorting
        // where you save the indexes and then match them to corresponding char Arr indexes
    }
}


The zipping way is an easy way, but for completeness another approach is to use an index array:

var letterArray = ['a', 'e', 'i', 'o', 'u'];
var valueArray = [12, 22, 7, 7, 3];
var indexArray = [0, 1, 2, 3, 4]; // normally you would compute this dynamically
indexArray.sort(function(a, b) { return valueArray[a] - valueArray[b]; });

To retrieve an array of the letters sorted by value order you would need to loop through the indexArray retrieving the letter at each index.


If I were to do this, instead of using two arrays I would use one array of objects.. Then you can make your own sort comparison function and that will give you the most control over your data structure.

letters_and_values = [{letter: 'a', value: 12},
                      {letter: 'e', value: 22},
                      {letter: 'i', value: 7},
                      {letter: 'o', value: 7},
                      {letter: 'u', value: 3}];

function valueCompare(obj1, obj2) {
    if (obj1.value < obj2.value) {
        return 1;
    }
    else if (obj1.value > obj2.value) {
        return -1;
    }
    else { 
        return 0;
    }
}

letters_and_values.sort(valueCompare);

// => [Object { letter="e", value=22}, 
//     Object { letter="a", value=12},
//     Object { letter="i", value=7}, 
//     Object { letter="o", value=7}, 
//     Object { letter="u", value=3}]
0

精彩评论

暂无评论...
验证码 换一张
取 消