以相同的方式对两个数组排序

时间:2012-07-16 06:43:07

标签: javascript

例如,如果我有这些数组:

var name = ["Bob","Tom","Larry"];
var age =  ["10", "20", "30"];

我使用name.sort()“name”数组的顺序变为:

var name = ["Bob","Larry","Tom"];

但是,如何对“name”数组进行排序并使“age”数组保持相同的顺序?像这样:

var name = ["Bob","Larry","Tom"];
var age =  ["10", "30", "20"];

12 个答案:

答案 0 :(得分:50)

您可以对现有阵列进行排序,也可以重新组织数据。

方法1: 要使用现有数组,您可以对它们进行组合,排序和分离: (假设等长阵列)

var names = ["Bob","Tom","Larry"];
var ages =  ["10", "20", "30"];

//1) combine the arrays:
var list = [];
for (var j = 0; j < names.length; j++) 
    list.push({'name': names[j], 'age': ages[j]});

//2) sort:
list.sort(function(a, b) {
    return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
    //Sort could be modified to, for example, sort on the age 
    // if the name is the same.
});

//3) separate them back out:
for (var k = 0; k < list.length; k++) {
    names[k] = list[k].name;
    ages[k] = list[k].age;
}

这样做的好处是不依赖于字符串解析技术,并且可以在需要一起排序的任意数量的数组上使用。

方法2:或者您可以稍微重新组织数据,只需对对象集合进行排序:

var list = [
    {name: "Bob", age: 10}, 
    {name: "Tom", age: 20},
    {name: "Larry", age: 30}
    ];

list.sort(function(a, b) {
    return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});

for (var i = 0; i<list.length; i++) {
    alert(list[i].name + ", " + list[i].age);
}
​

对于比较,-1表示较低的索引,0表示相等,1表示较高的索引。值得注意的是sort()实际上更改了底层数组。

http://jsfiddle.net/ghBn7/38/

答案 1 :(得分:2)

你试图通过在其中一个上调用sort()来对2个独立数组进行排序。

实现这一目标的一种方法是编写自己的排序方法,这将解决这个问题,这意味着当它在“原始”数组中就地交换2个元素时,它应该在“属性”中就地交换2个元素“阵列。

以下是关于如何尝试它的伪代码。

function mySort(originals, attributes) {
    // Start of your sorting code here
        swap(originals, i, j);
        swap(attributes, i, j);
    // Rest of your sorting code here
}

答案 2 :(得分:2)

我遇到了同样的问题,想出了这个非常简单的解决方案。首先将关联的元素组合成一个单独的数组中的字符串,然后在排序比较函数中使用parseInt,如下所示:

<html>
<body>
<div id="outPut"></div>
<script>
var theNums = [13,12,14];
var theStrs = ["a","b","c"];
var theCombine = [];

for (var x in theNums)
{
    theCombine[x] = theNums[x] + "," + theStrs;
}

var theSorted = theAr.sort(function(a,b)
{
    var c = parseInt(a,10);
    var d = parseInt(b,10);
    return c-d;
});
document.getElementById("outPut").innerHTML = theS;
</script>
</body>
</html>

答案 3 :(得分:1)

@jwatts1980's answer启发,@Alexander's answer here我将两个答案合并为快速而肮脏的解决方案; 主数组是要排序的数组,其余数组只跟随其索引

注意:对于非常大的数组来说效率不高

 /* @sort argument is the array that has the values to sort
   @followers argument is an array of arrays which are all same length of 'sort'
   all will be sorted accordingly
   example:

   sortMutipleArrays(
         [0, 6, 7, 8, 3, 4, 9], 
         [ ["zr", "sx", "sv", "et", "th", "fr", "nn"], 
           ["zero", "six", "seven", "eight", "three", "four", "nine"] 
         ]
   );

  // Will return

  {  
     sorted: [0, 3, 4, 6, 7, 8, 9], 
     followed: [
      ["zr", th, "fr", "sx", "sv", "et", "nn"], 
      ["zero", "three", "four", "six", "seven", "eight", "nine"]
     ]
   }
 */

您可能想要更改方法签名/返回结构,但这应该很容易。我是这样做的,因为我需要它

var sortMultipleArrays = function (sort, followers) {
  var index = this.getSortedIndex(sort)
    , followed = [];
  followers.unshift(sort);
  followers.forEach(function(arr){
    var _arr = [];
    for(var i = 0; i < arr.length; i++)
      _arr[i] = arr[index[i]];
    followed.push(_arr);
  });
  var result =  {sorted: followed[0]};
  followed.shift();
  result.followed = followed;
  return result;
};

var getSortedIndex = function (arr) {
  var index = [];
  for (var i = 0; i < arr.length; i++) {
    index.push(i);
  }
  index = index.sort((function(arr){
  /* this will sort ints in descending order, change it based on your needs */
    return function (a, b) {return ((arr[a] > arr[b]) ? -1 : ((arr[a] < arr[b]) ? 1 : 0));
    };
  })(arr));
  return index;
};

答案 4 :(得分:1)

jwatts1980's answer (Update 2)非常相似。 考虑阅读Sorting with map

name.map(function (v, i) {
    return {
        value1  : v,
        value2  : age[i]
    };
}).sort(function (a, b) {
    return ((a.value1 < b.value1) ? -1 : ((a.value1 == b.value1) ? 0 : 1));
}).forEach(function (v, i) {
    name[i] = v.value1;
    age[i] = v.value2;
});

答案 5 :(得分:1)

我正在寻找比当前答案更通用和更实用的东西。

这就是我提出的:es6实现(没有突变!),它允许您根据需要对“源”数组进行排序。

/**
 * Given multiple arrays of the same length, sort one (the "source" array), and
 * sort all other arrays to reorder the same way the source array does.
 * 
 * Usage:
 * 
 * sortMultipleArrays( objectWithArrays, sortFunctionToApplyToSource )
 * 
 * sortMultipleArrays(
 *   {
 *    source: [...],
 *    other1: [...],
 *    other2: [...]
 *   },
 *   (a, b) => { return a - b })
 * )
 * 
 * Returns:
 *   {
 *      source: [..sorted source array]
 *      other1: [...other1 sorted in same order as source],
 *      other2: [...other2 sorted in same order as source]
 *   }
 */
export function sortMultipleArrays( namedArrays, sortFn ) {
    const { source } = namedArrays;
    if( !source ) {
        throw new Error('You must pass in an object containing a key named "source" pointing to an array');
    }

    const arrayNames = Object.keys( namedArrays );

    // First build an array combining all arrays into one, eg
    // [{ source: 'source1', other: 'other1' }, { source: 'source2', other: 'other2' } ...]
    return source.map(( value, index ) =>
        arrayNames.reduce((memo, name) => ({
            ...memo,
            [ name ]: namedArrays[ name ][ index ]
        }), {})
    )
    // Then have user defined sort function sort the single array, but only
    // pass in the source value
    .sort(( a, b ) => sortFn( a.source, b.source ))
    // Then turn the source array back into an object with the values being the
    // sorted arrays, eg
    // { source: [ 'source1', 'source2' ], other: [ 'other1', 'other2' ] ... }
    .reduce(( memo, group ) =>
        arrayNames.reduce((ongoingMemo, arrayName) => ({
            ...ongoingMemo,
            [ arrayName ]: [
                ...( ongoingMemo[ arrayName ] || [] ),
                group[ arrayName ]
            ]
        }), memo), {});
}

答案 6 :(得分:1)

您可以使用nameArray.from(name.keys())获得[...name.keys()]数组的索引。根据{{​​1}}的值对它们进行排序。然后使用indices获取任意数量的相关数组中相应索引的值

map

这是一个片段:

const indices = Array.from(name.keys())
indices.sort( (a,b) => name[a].localeCompare(name[b]) )

const sortedName = indices.map(i => name[i]),
const sortedAge = indices.map(i => age[i])

答案 7 :(得分:0)

您可以将每个成员的原始索引附加到值,对数组进行排序,然后删除索引并使用它来重新排序其他数组。它只能在内容为字符串的情况下工作,或者可以成功地转换为字符串和字符串。

另一种解决方案是保留原始数组的副本,然后在排序后,找到每个成员现在的位置并适当调整另一个数组。

答案 8 :(得分:0)

最简单的解释是最好的,合并数组,然后在排序后提取: 创建一个数组

name_age=["bob@10","Tom@20","Larry@30"];

像以前那样对数组进行排序,然后提取名称和年龄,您可以使用@来重新定位 名称结束,年龄开始。也许不是纯粹主义者的方法,但我有同样的问题和我的方法。

答案 9 :(得分:0)

如果性能很重要,那么可以使用sort-ids软件包:

var sortIds = require('sort-ids')
var reorder = require('array-rearrange')

var name = ["Bob","Larry","Tom"];
var age =  [30, 20, 10];

var ids = sortIds(age)
reorder(age, ids)
reorder(name, ids)

那是比较器功能的约5倍。

答案 10 :(得分:0)

此解决方案(我的工作)可以对多个数组进行排序,而无需将数据转换为中间结构,并且可以有效地处理大型数组。它允许将数组作为列表或对象传递,并支持自定义的compareFunction。

用法:

let people = ["john", "benny", "sally", "george"];
let peopleIds = [10, 20, 30, 40];

sortArrays([people, peopleIds]);
[["benny", "george", "john", "sally"], [20, 40, 10, 30]] // output

sortArrays({people, peopleIds});
{"people": ["benny", "george", "john", "sally"], "peopleIds": [20, 40, 10, 30]} // output

算法:

  • 创建主数组(sortableArray)的索引列表
  • 使用自定义的compareFunction对索引进行排序,该比较函数对值进行比较,并通过索引进行查找
  • 对于每个输入数组,将每个索引依次映射到其值

实施:

/**
 *  Sorts all arrays together with the first. Pass either a list of arrays, or a map. Any key is accepted.
 *     Array|Object arrays               [sortableArray, ...otherArrays]; {sortableArray: [], secondaryArray: [], ...}
 *     Function comparator(?,?) -> int   optional compareFunction, compatible with Array.sort(compareFunction)
 */
function sortArrays(arrays, comparator = (a, b) => (a < b) ? -1 : (a > b) ? 1 : 0) {
    let arrayKeys = Object.keys(arrays);
    let sortableArray = Object.values(arrays)[0];
    let indexes = Object.keys(sortableArray);
    let sortedIndexes = indexes.sort((a, b) => comparator(sortableArray[a], sortableArray[b]));

    let sortByIndexes = (array, sortedIndexes) => sortedIndexes.map(sortedIndex => array[sortedIndex]);

    if (Array.isArray(arrays)) {
        return arrayKeys.map(arrayIndex => sortByIndexes(arrays[arrayIndex], sortedIndexes));
    } else {
        let sortedArrays = {};
        arrayKeys.forEach((arrayKey) => {
            sortedArrays[arrayKey] = sortByIndexes(arrays[arrayKey], sortedIndexes);
        });
        return sortedArrays;
    }
}

另请参阅https://gist.github.com/boukeversteegh/3219ffb912ac6ef7282b1f5ce7a379ad

答案 11 :(得分:0)

怎么样:

var names = ["Bob","Tom","Larry"];
var ages =  ["10", "20", "30"];
var n = names.slice(0).sort()
var a = [];
for (x in n)
{
i = names.indexOf(n[x]);
a.push(ages[i]);
names[i] = null;
}
names = n
ages = a