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
Assign new value to item in an array if it matches another item without looping in JavaScript?
In JavaScript, you can assign a new value to an array item that matches a condition without using traditional loops. This can be achieved using array methods like filter() combined with map(), or more efficiently with forEach() or find().
Using filter() and map()
The filter() method finds matching items, and map() modifies them. Here's how to change "Bob" to "Carol" in an array of objects:
const studentDetails = [
{Name: "John"},
{Name: "David"},
{Name: "Bob"},
{Name: "Mike"}
];
var changeName = "Bob";
studentDetails.filter((obj) => obj.Name === changeName).map((obj) =>
obj.Name = "Carol");
console.log(studentDetails);
[
{ Name: 'John' },
{ Name: 'David' },
{ Name: 'Carol' },
{ Name: 'Mike' }
]
Using forEach() (More Efficient)
The forEach() method is more efficient as it doesn't create intermediate arrays:
const studentDetails = [
{Name: "John"},
{Name: "David"},
{Name: "Bob"},
{Name: "Mike"}
];
studentDetails.forEach(obj => {
if (obj.Name === "Bob") {
obj.Name = "Carol";
}
});
console.log(studentDetails);
[
{ Name: 'John' },
{ Name: 'David' },
{ Name: 'Carol' },
{ Name: 'Mike' }
]
Using find() for Single Match
If you only need to update the first matching item, find() is most efficient:
const studentDetails = [
{Name: "John"},
{Name: "David"},
{Name: "Bob"},
{Name: "Mike"}
];
const student = studentDetails.find(obj => obj.Name === "Bob");
if (student) {
student.Name = "Carol";
}
console.log(studentDetails);
[
{ Name: 'John' },
{ Name: 'David' },
{ Name: 'Carol' },
{ Name: 'Mike' }
]
Comparison
| Method | Performance | Use Case |
|---|---|---|
filter() + map() |
Slowest | Multiple matches, functional style |
forEach() |
Good | Multiple matches needed |
find() |
Best | Single match only |
Conclusion
Use find() for single updates and forEach() for multiple matches. The filter() + map() approach works but is less efficient due to creating intermediate arrays.
Advertisements
