简体   繁体   中英

Is there an efficient way to add an Array element's original index value as a property when sorting by another property in JavaScript?

AI have an Array that I am sorting by title property:

    theArray.sort(function(a, b) {
        var titleA = a.title.toLowerCase();
        var titleB = b.title.toLowerCase();
        return (titleA < titleB) ? -1 : (titleA > titleB) ? 1 : 0;
    });

That works fine, but in addition to getting the sorted Array I'd like to also preserve the original Array index values for another purpose (they point to yet another Array). I'd like to store that as a property.idx in each element of the Array.

Of course I could simply add that property before sorting, by doing this:

for (var i=0; i<theArray.length; i++) {theArray.index = i);

This would be somewhat wasteful in this case because I don't always need to sort the Array. And when originally creating the Array it's coming from some JSON that doesn't have that property included. So I was thinking it might be best if I could add the property while sorting.

Any ideas? Thanks.

Instead of sorting the original array, you could sort an array of indicies :

const getTitle = i => theArray[i].title.toLowerCase();
const indicies = theArray.map((_, i) => i);
indicies.sort((indA, indB) => getTitle(indB).localeCompare(getTitle(indA)));

Then, when you need to do something with the "sorted" array, iterate over the indicies and access theArray[i] . When you need to do something with the sorted indicies, just iterate over the indicies array.

Create a new array when sorting, using spread will help:

const newArray = [...theArray].sort(function(a, b) {
  var titleA = a.title.toLowerCase();
  var titleB = b.title.toLowerCase();
  return (titleA < titleB) ? -1 : (titleA > titleB) ? 1 : 0;
});

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