- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ]
Advertisements