61

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

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"];
4

12 回答 12

79

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

方法一: 使用已有的数组,可以组合、排序、分离:( 假设等长数组)

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()实际上改变了底层数组。

另外值得注意的是,方法 2 更有效,因为除了排序之外,您不必遍历整个列表两次。

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

于 2012-07-16T06:52:58.583 回答
6

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

于 2019-07-25T08:48:00.510 回答
6

您可以使用or获取name数组的索引。根据它们的值对它们进行排序。然后用于获取任意数量相关数组中相应索引的值Array.from(name.keys())[...name.keys()]indicesmap

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])

这是一个片段:

const name = ["Bob","Tom","Larry"],
      age =  ["10", "20", "30"],
      
      indices = Array.from(name.keys())
                     .sort( (a,b) => name[a].localeCompare(name[b]) ),
                     
      sortedName = indices.map(i => name[i]),
      sortedAge = indices.map(i => age[i])

console.log(indices)
console.log(sortedName)
console.log(sortedAge)

于 2020-09-14T14:44:23.937 回答
3

如果性能很重要,可以使用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 倍。

于 2018-11-18T06:07:12.807 回答
2

它与jwatts1980 的回答 (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;
});
于 2015-06-20T11:33:22.860 回答
1

您试图通过仅在其中一个上调用 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
}
于 2012-07-16T06:49:17.197 回答
1

@jwatts1980 的回答@Alexander的回答启发,我将这两个答案合并为一个快速而肮脏的解决方案;主数组是要排序的,其余的只是按照它的索引

注意:对于非常非常大的阵列不是很有效

 /* @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;
};
于 2013-06-14T17:12:30.077 回答
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), {});
}
于 2018-04-15T22:11:04.113 回答
0

您可以将每个成员的原始索引附加到值,对数组进行排序,然后删除索引并使用它重新排序另一个数组。它仅适用于内容是字符串或可以成功转换为字符串和从字符串转换的情况。

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

于 2012-07-16T07:10:33.337 回答
0

我遇到了同样的问题,并想出了这个非常简单的解决方案。首先将关联的元素组合成单独数组中的字符串,然后在排序比较函数中使用 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>
于 2016-02-07T15:45:21.733 回答
-1

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

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

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

于 2014-12-06T23:42:30.870 回答
-1

怎么样:

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
于 2019-08-20T18:33:54.497 回答