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
Sort by index of an array in JavaScript
Sorting an array of objects by a specific property is a common task in JavaScript. This tutorial demonstrates how to sort objects by their index property and extract specific values.
Problem Statement
Suppose we have the following array of objects:
const arr = [
{
'name': 'd',
'index': 3
},
{
'name': 'c',
'index': 2
},
{
'name': 'a',
'index': 0
},
{
'name': 'b',
'index': 1
}
];
We need to sort this array by the index property in ascending order, then extract the name values into a new array.
Expected Output
The final result should be:
["a", "b", "c", "d"]
Solution
Here's a complete solution that sorts by index and maps to names:
const arr = [
{
'name': 'd',
'index': 3
},
{
'name': 'c',
'index': 2
},
{
'name': 'a',
'index': 0
},
{
'name': 'b',
'index': 1
}
];
const sortAndMap = (arr = []) => {
const copy = arr.slice();
const sorter = (a, b) => {
return a['index'] - b['index'];
};
copy.sort(sorter);
const res = copy.map(({name, index}) => {
return name;
});
return res;
};
console.log(sortAndMap(arr));
[ 'a', 'b', 'c', 'd' ]
How It Works
The solution involves three main steps:
-
Create a copy:
arr.slice()creates a shallow copy to avoid modifying the original array -
Sort by index: The compare function
(a, b) => a.index - b.indexsorts in ascending order -
Extract names:
map()with destructuring extracts only the name property from each object
Alternative Approach: One-liner
You can achieve the same result in a more concise way:
const arr = [
{ 'name': 'd', 'index': 3 },
{ 'name': 'c', 'index': 2 },
{ 'name': 'a', 'index': 0 },
{ 'name': 'b', 'index': 1 }
];
const result = arr
.slice()
.sort((a, b) => a.index - b.index)
.map(item => item.name);
console.log(result);
[ 'a', 'b', 'c', 'd' ]
Key Points
- Always create a copy with
.slice()before sorting to preserve the original array - The compare function
(a, b) => a.property - b.propertysorts numerically in ascending order - Use
.map()to transform the sorted array into the desired format - Destructuring in the map function
({name}) => nameprovides cleaner syntax
Conclusion
Sorting objects by index and mapping to specific properties is accomplished using sort() with a custom compare function and map(). Always work with a copy to avoid side effects on the original data.
