Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create an ordered array from values that have an order number in JavaScript?
When working with arrays containing values and order numbers, you often need to sort them by their order and extract just the values. This is common when dealing with image galleries, menu items, or any data that needs custom ordering.
Problem Setup
Let's say we have an array of strings where each string contains a file path and an order number separated by a comma:
const images = [
'photo1.jpg,0',
'photo2.jpg,2',
'photo3.jpg,1'
];
console.log("Original array:", images);
Original array: [ 'photo1.jpg,0', 'photo2.jpg,2', 'photo3.jpg,1' ]
We need to sort by the order numbers (0, 1, 2) and extract just the file paths, resulting in: ['photo1.jpg', 'photo3.jpg', 'photo2.jpg']
Solution: Sort and Extract
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("Ordered array:", sortArray(images));
Ordered array: [ 'photo1.jpg', 'photo3.jpg', 'photo2.jpg' ]
How It Works
The solution works in three steps:
- slice() - Creates a copy to avoid mutating the original array
- sort(sorter) - Sorts by comparing the order numbers (second part after comma)
- map() - Extracts just the file paths (first part before comma)
Alternative: More Readable Version
const images = [
'photo1.jpg,0',
'photo2.jpg,2',
'photo3.jpg,1'
];
function createOrderedArray(items) {
return items
.map(item => {
const [path, order] = item.split(',');
return { path, order: parseInt(order) };
})
.sort((a, b) => a.order - b.order)
.map(item => item.path);
}
console.log("Result:", createOrderedArray(images));
Result: [ 'photo1.jpg', 'photo3.jpg', 'photo2.jpg' ]
Conclusion
Use split(), sort(), and map() to parse, order, and extract values from comma-separated strings. The slice() method ensures the original array remains unchanged.
Advertisements
