Access previously iterated element within array.map in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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'
   }
]
raja
Published on 31-Aug-2020 13:52:12
Advertisements