- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access previously iterated element within array.map in JavaScript?
Let’s say the following is our array −
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'Javascript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ];
Now, use the concept of map(). The code is as follows −
Example
var details = [ {subjectId:110, subjectName: 'Java' }, {subjectId:111, subjectName: 'JavaScript' }, {subjectId:112, subjectName: 'MySQL' }, {subjectId:113, subjectName: 'MongoDB' } ]; var output = details.map((detailsObject, index) => { var tempObject = {}; tempObject.subjectId= detailsObject.subjectId; tempObject.subjectName = detailsObject.subjectName; const getThePreviousObject = index != 0 ? details[index-1] : null; tempObject.previousSubjectName = getThePreviousObject ? getThePreviousObject.subjectName : 'Not Available' return tempObject; }) console.log(output);
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo204.js.
Output
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo204.js [ { subjectId: 110, subjectName: 'Java', previousSubjectName: 'Not Available' }, { subjectId: 111, subjectName: 'JavaScript', previousSubjectName: 'Java' }, { subjectId: 112, subjectName: 'MySQL', previousSubjectName: 'JavaScript' }, { subjectId: 113, subjectName: 'MongoDB', previousSubjectName: 'MySQL' } ]
Advertisements