John Doe John Doe - 1 month ago 9
Javascript Question

How to create an ordered array from values that have an order number?

So I have a series of strings, which contain and image path and order # concatenated.

They look like this:

const images = [
'photo1.jpg,0'
'photo2.jpg,2'
'photo3.jpg,1'
]


So the correct order should be: photo1, photo3, photo2.

What I need to do is process this into a correctly ordered array with just the path values. So ultimately I need:

const orderedImages = [
'photo1.jpg'
'photo3.jpg'
'photo2.jpg'
]


What is the best way to do this?

Answer

You can use array.sort to order them and array.map to remove order value.

const images = [
  'photo1.jpg,0',
  'photo2.jpg,2',
  'photo3.jpg,1'
]
var output = images.sort(function(a,b){
  return +a.split(',')[1] - +b.split(',')[1]
}).map(function(item){
  return item.split(',')[0]
});

console.log(output)