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
Finding content of arrays on the basis of specific property in JavaScript?
When working with arrays of objects in JavaScript, you often need to find and merge content based on matching properties. The find() method combined with map() provides an effective solution for this common task.
Understanding the Problem
Consider two arrays of student records where you want to find matching students based on their roll numbers and merge or replace data from the second array when matches are found.
Using map() with find()
The map() method creates a new array by transforming each element, while find() searches for the first matching element in another array.
var firstObject = [
{ "FirstName": "David", "RollNo": "105", "Subject": "MongoDB" },
{ "FirstName": "Mike", "RollNo": "110", "Subject": "JavaScript"}
];
var secondObject = [
{ "FirstName": "Bob", "RollNo": "101", "Subject": "Java" },
{ "FirstName": "John", "RollNo": "110", "Subject": "MySQL" }
];
var output = firstObject.map(first =>
(secondObject.find(second => second.RollNo == first.RollNo) || first)
);
console.log(output);
[
{ FirstName: 'David', RollNo: '105', Subject: 'MongoDB' },
{ FirstName: 'John', RollNo: '110', Subject: 'MySQL' }
]
How It Works
The code works by:
- Iterating through each element in
firstObjectusingmap() - For each element, using
find()to search for a matchingRollNoinsecondObject - If a match is found, replacing the original element with the matched one
- If no match is found, keeping the original element using the logical OR operator (
||)
Alternative Approach: Filter and Find
You can also filter arrays based on specific property conditions:
var students = [
{ "Name": "Alice", "Grade": "A", "Subject": "Math" },
{ "Name": "Bob", "Grade": "B", "Subject": "Science" },
{ "Name": "Charlie", "Grade": "A", "Subject": "Math" }
];
// Find all students with Grade "A"
var topStudents = students.filter(student => student.Grade === "A");
console.log("Top students:", topStudents);
// Find first student studying Math
var mathStudent = students.find(student => student.Subject === "Math");
console.log("First Math student:", mathStudent);
Top students: [
{ Name: 'Alice', Grade: 'A', Subject: 'Math' },
{ Name: 'Charlie', Grade: 'A', Subject: 'Math' }
]
First Math student: { Name: 'Alice', Grade: 'A', Subject: 'Math' }
Conclusion
Combining map() with find() provides a powerful way to merge or update array elements based on matching properties. This pattern is commonly used for data synchronization and lookup operations in JavaScript applications.
