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

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
raja
Published on 26-Aug-2020 15:00:28
Advertisements