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


Let’s say, we 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'
];

Therefore, the correct order should be − photo1, photo3, photo2. What we need to do is process this into a correctly ordered array with just the path values. So, ultimately we need −

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

Let’s write the code to sort this array of images according to its correct order −

Example

const images = [
   'photo1.jpg,0',
   'photo2.jpg,2',
   'photo3.jpg,1'
];
const sorter = (a, b) => {
   return parseInt(a.split(",")[1]) - parseInt(b.split(",")[1]);
};
const sortArray = arr => {
   return arr
   .slice()
   .sort(sorter)
   .map(el => {
      return el.split(",")[0];
   });
};
console.log(sortArray(images));

Output

The output in the console will be −

[ 'photo1.jpg', 'photo3.jpg', 'photo2.jpg' ]

Updated on: 26-Aug-2020

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements