Sort two arrays the same way

前端 未结 12 2205
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 15:48

For example, if I have these arrays:

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

And I use name.sort

相关标签:
12条回答
  • 2020-11-27 16:22

    Simplest explantion is the best, merge the arrays, and then extract after sorting: create an array

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

    sort the array as before, then extract the name and the age, you can use @ to reconise where name ends and age begins. Maybe not a method for the purist, but I have the same issue and this my approach.

    0 讨论(0)
  • 2020-11-27 16:24

    You are trying to sort 2 independet arrays by only calling sort() on one of them.

    One way of achieving this would be writing your own sorting methd which would take care of this, meaning when it swaps 2 elements in-place in the "original" array, it should swap 2 elements in-place in the "attribute" array.

    Here is a pseudocode on how you might try it.

    function mySort(originals, attributes) {
        // Start of your sorting code here
            swap(originals, i, j);
            swap(attributes, i, j);
        // Rest of your sorting code here
    }
    
    0 讨论(0)
  • 2020-11-27 16:28

    How about:

    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
    
    0 讨论(0)
  • 2020-11-27 16:32

    It is very similar to jwatts1980's answer (Update 2). Consider reading 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;
    });
    
    0 讨论(0)
  • 2020-11-27 16:32

    I was looking for something more generic and functional than the current answers.

    Here's what I came up with: an es6 implementation (with no mutations!) that lets you sort as many arrays as you want given a "source" array

    /**
     * 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), {});
    }
    
    0 讨论(0)
  • 2020-11-27 16:34

    You could append the original index of each member to the value, sort the array, then remove the index and use it to re-order the other array. It will only work where the contents are strings or can be converted to and from strings successfuly.

    Another solution is keep a copy of the original array, then after sorting, find where each member is now and adjust the other array appropriately.

    0 讨论(0)
提交回复
热议问题