简体   繁体   中英

How to sort JavaScript array items by same position in second array?

I have two types of arrays,

With the same number of items, in one are a plane array in the second I have their new indexes.

First array:

let arrayOfPersons = [
 {
    myName: "Person 0"
 },
 {
    myName: "Person 1"
 }
....
];

Indexes have defaulted from 0 to n.

A new array of the new indexes:

let newIndexOfPerson = [
    { 
      myName: "Person 0" // or just old index 0 from array above
      newPersonIndex: 1
    }
....
];

So, How I can sort objects with their old indexes (from 0 to n) with new index in the newIndexOfPerson array?

Thank you!

So, you'd like to sort array newIndexOfPerson by newPersonIndex?

You could use javascript method sort(), so you don't need to write complex functions by yourself. check sort() method from MDN

the code you'd like to have would be something like this.

newIndexOfPerson.sort((a, b) => (a.newPersonIndex> b.newPersonIndex) ? 1 : -1);

One side-effect of using sort on the newIndexOfPerson is that it performs sorting in place , rather than returning a new array with the entries sorted, so newIndexOfPerson array itself will be modified.

If this is unwanted, you may sort a copy of this array (use newIndexOfPerson.slice() to make one).

However, if you really need 2 arrays to read data from and you know the correct indecies to begin with, rather than trying sort with a custom sorter, it may be more elegant and faster to use reduce to create a new array and fill its entries according to the indecies and data specified in newIndexOfPerson :

arrayOfPersons = newIndexOfPerson.reduce((newArrayOfPersons, entry) => {
        newArrayOfPersons[entry.newPersonIndex] = {
            myName: entry.myName
        };
        return newArrayOfPersons;
    }, 
    new Array(arrayOfPersons.length)
);

This code has linear time complexity, while sort has logarithmic complexity.

It can be easily modified work with "old indecies" in newIndexOfPerson instead of just plain data. This solution, of course, expects that the lengths of arrays match and all the indecies are set correctly (otherwise, you'll get gaps in the resulting array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM