How to use reduce Method() In Javascript
Reduce method also use to iterate over an array and create a single value and object,
Example: In this example, we are using reduce method to create a partial object from another array.
let studentDetails = [
{
name: 'dinesh',
age: 20,
marks: 30,
},
{
name: 'divi',
age: 20,
marks: 60,
},
{
name: 'vignesh',
age: 30,
marks: 80,
}]
const partialStudentDetails = studentDetails.reduce((res, item) => {
res.push({ name: item.name, age: item.age, marks: item.marks });
return res;
}, []);
console.log(partialStudentDetails);
Output
[ { name: 'dinesh', age: 20, marks: 30 }, { name: 'divi', age: 20, marks: 60 }, { name: 'vignesh', age: 30, marks: 80 } ]
How to create an array of partial objects from another array in JavaScript ?
Creating an array of partial objects from another array is a useful technique in JavaScript, especially for data transformation and manipulation. This guide covers various methods to efficiently create these arrays, enhancing your ability to work with complex data structures.
Importance of Creating Partial Objects:
Creating partial objects is crucial for:
- Simplifying data structures for specific use cases.
- Improving performance by reducing the size of data handled.
- Enhancing readability and maintainability of code by focusing on relevant properties.
These are some common methods:
Table of Content
- Using the map() method
- Using Destructuring
- Using reduce Method()
- Using forEach() method
- Using a for Loop