Easy way to sort 2 arrays in Javascript?

Sorry if this is a stupid question, but I'm learning JavaScript and wondering if there is an easy way to sort 2 lists, like the following:

var names=["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
var points=[12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];

      

How do I display items from "names" according to their corresponding value in "dots"? For example, for the above item6

will be displayed first and item5

will be displayed last.

+3


source to share


3 answers


I don't know if this is enough, but you can create an array of objects, sort it with a value

prop and just a map to only get the props name

.



let names = ["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"],
    points = [12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101],
    
    res = names.map((v, i) => ({ name: v, val: points[i] }))
               .sort((a, b) => b.val - a.val)
               .map(v => v.name);
    
    console.log(res);
      

Run codeHide result


+2


source


Here's a somewhat lengthy solution (with a much more concise version below). The basic idea is as follows:

  • Sorting an array points

    in descending order
  • Loop through the sorted array and find each value position in the original array points

  • Take the corresponding element from the array names

  • Enter value into new array

var names=["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
var points=[12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];

const sortedPoints = points.slice().sort(function(a, b) {
  return b - a;
});

const sortedNames = [];
sortedPoints.forEach(function(val) {
  const position = points.indexOf(val);
  sortedNames.push(names[position]);
})

console.log(sortedNames)
      

Run codeHide result




For a more concise solution, following the same process but using some shortcuts:

const names = ["item", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"];
const points = [12, 12345, 5765, 123, 3, 567765, 99, 87654, 881, 101];

const sortedNames = points.slice().sort((a, b) => b - a).map(val => names[points.indexOf(val)]);

console.log(sortedNames)
      

Run codeHide result


0


source


Javascript has no zip function natively. But that's most of what you want to do here. A small utility library like underscore is very handy. You can view the annotated source if you just want to replicate the zip function yourself.

var zippedAndSorted = _.zip(names, points)
.sort(function(a, b) {
    return b - a;
});

      

Then you can iterate over each pair:

zippedAndSorted.forEach(function(namePoint) {
    console.log('Name: ' + namePoint[0] + ' Points: ' + namePoint[1]);
});

      

0


source







All Articles