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
Display resultant array based on the object's order determined by the first array in JavaScript?
When working with objects and arrays in JavaScript, you often need to reorder data based on a specific sequence. This article shows how to use an array to determine the order of values extracted from an object using the map() method.
The Problem
Consider an object containing key-value pairs and an array that defines the desired order. We want to create a new array with values from the object, ordered according to the array sequence.
// Object with key-value pairs
var lastName = {
"John": "Smith",
"David": "Miller",
"Bob": "Taylor"
}
// Array defining the desired order
var firstName = [
"Bob",
"John",
"David"
]
console.log("Original object:", lastName);
console.log("Order array:", firstName);
Original object: { John: 'Smith', David: 'Miller', Bob: 'Taylor' }
Order array: [ 'Bob', 'John', 'David' ]
Using map() to Reorder Values
The map() method creates a new array by transforming each element. We can use it to extract object values in the order specified by our array:
var firstName = [
"Bob",
"John",
"David"
]
var lastName = {
"John": "Smith",
"David": "Miller",
"Bob": "Taylor"
}
// Map through firstName array and get corresponding lastName values
var values = firstName.map(name => lastName[name]);
console.log("Resultant array:", values);
Resultant array: [ 'Taylor', 'Smith', 'Miller' ]
How It Works
The map() method iterates through each element in the firstName array:
- First iteration:
name = "Bob"?lastName["Bob"]?"Taylor" - Second iteration:
name = "John"?lastName["John"]?"Smith" - Third iteration:
name = "David"?lastName["David"]?"Miller"
Alternative Approaches
You can also use a traditional for loop or forEach method:
// Using for loop
var values1 = [];
for (let i = 0; i {
values2.push(lastName[name]);
});
console.log("For loop result:", values1);
console.log("forEach result:", values2);
For loop result: [ 'Taylor', 'Smith', 'Miller' ] forEach result: [ 'Taylor', 'Smith', 'Miller' ]
Comparison
| Method | Returns New Array | Code Length | Readability |
|---|---|---|---|
map() |
Yes | Short | High |
for loop |
No (manual push) | Medium | Medium |
forEach() |
No (manual push) | Medium | High |
Conclusion
Using map() with object property access provides an elegant solution for reordering object values based on array sequences. This pattern is commonly used in data transformation and sorting operations.
