Retrieve the element that was previously processed in array.map

When working with JavaScript, I have an array of objects containing ids, names, and other properties that I am iterating over to create a new object with modified properties. One specific requirement is that one property should be related to the last iterated element, like its predecessor. For example:

let returnedArrOfObjs = [{id: 1, name: 'first', predecessor: 'none' },
{id: 2, name: 'second', predecessor:'first'}, 
{id: 3, name: 'third', predecessor: 'second'}] 

I am wondering if there is a way to access the previously iterated element?

The code snippet below doesn't work as prevObj is undefined, but it showcases my intention:

array.map(obj => {
        let rObj = {};
        rObj.id = obj.id,
        rObj.name = obj.name,
        rObj.predecessor = prevObj ? prevObj.name : 'none'
        return rObj;
    })

Answer №1

.map() has a second parameter called the current loop index. This allows you to access the last element in the loop using the following method:

let array = [{id: 1, name: 'first' },
{id: 2, name: 'second'}, 
{id: 3, name: 'third'}];


const result = array.map((obj, i) => { // include index in the function parameters
    let rObj = {};
    rObj.id = obj.id;
    rObj.name = obj.name;
    
    const prevObj = i != 0 ? array[i - 1] : null; // Check if the current index is not 0, then get the previous object
    rObj.predecessor = prevObj ? prevObj.name : 'none'
    return rObj;
})

console.log(result);

Answer №2

The map function in an array allows for a third argument to be passed in, which is the array itself. This can be utilized to access the previous item in the array:

const modifiedArray = array.map((item, index, originalArray) => {
    let newItem = {};
    newItem.id = item.id;
    newItem.name = item.name;

    // Retrieve the previous object only if it's not the first iteration:
    const previousItem = index != 0 
        ? originalArray[index - 1] 
        : null; 

    newItem.predecessor = previousItem ? previousItem.name : "none";
    return newItem;
});

Answer №3

Your solution is almost there, but the missing part is the second argument in map(). The second argument is the index position, which you can use to check if there is an element in the previous index. If there is, you can use its name, otherwise set it to none.

let arrOfObjs = [{id: 1, name: 'first' },
{id: 2, name: 'second'}, 
{id: 3, name: 'third'}] 

let returnedArrOfObjs=arrOfObjs .map((obj,index)=>{
    let rObj = {};
    rObj.id = obj.id,
    rObj.name = obj.name,
    rObj.predecessor = arrOfObjs [index-1] ? arrOfObjs [index-1].name : 'none'
    return rObj;
})

console.log(returnedArrOfObjs)

Answer №4

One alternative approach that comes to mind involves utilizing the Array.reduce method. This method allows you to preserve information from one iteration to the next using the return statement. However, it can sometimes result in a more complex solution compared to other methods.

let returnedArrOfObjs = [{id: 1, name: 'first', predecessor: 'none' },
{id: 2, name: 'second', predecessor:'first'}, 
{id: 3, name: 'third', predecessor: 'second'}] 

const { result } = returnedArrOfObjs.reduce(({ prevObj, result }, obj) => {
    let rObj = {};
    rObj.id = obj.id,
    rObj.name = obj.name,
    rObj.predecessor = prevObj ? prevObj.name : 'none'

    result = [ ...result, rObj ]

    return { prevObj: rObj, result }
}, { result: [] })

console.log(result)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for searching a sentence and making replacements under certain conditions?

When it comes to the address: _# _, and for the specified phrase: _# some specific words _. I am looking to identify a phrase. if (phrase includes address) then delete the address. const stringVal = "being _#kind_, I am a _#kind_ _#man_, I love _#kind ...

The custom service is failing to load, in the simplest terms possible

After creating a dataService.j that contains the following: angular.module('dataService', []) .service('gameDataService', function() { var _gameData = { loggedIn: "false", gameJoined:"false", tableFu ...

Using Jest's moduleNameMapper with Next.js without TypeScript

I've been encountering some challenges trying to implement moduleNameMapper in NextJS using JavaScript. In this particular project, TypeScript is not being utilized. Next: 12.2.5 React: 18.2.0 Jest: 29.0.1 Jest environment jsdom: 29.0.1 Below is the ...

Caution: Always remember to surround any utilization of a keyed object

I can't figure out what's causing the warning in my code. It says Any use of a keyed object should be wrapped class GreetingsComponent extends React.Component { constructor(){ super() this.handleInput = this.handleInput.bind(this) ...

Generating a fresh instance of a class that mirrors an already existing instance, all without relying on eval()

I have an object named uniqueObject of an unspecified class and I am in need of creating a duplicate object from the same class. Here's my current approach: I extract the class name using uniqueObject.constructor.name. Then, I generate a new object o ...

Remembering previous scroll position with jScroll upon revisiting page

I'm implementing infinite scrolling of products on our site using jQuery jScroll. Can anyone guide me on how to save the scroll position when the user returns to the homepage? Appreciate any assistance! ...

Can the chrome console be used to showcase the contents of objects?

When I have a line of code, and I try to output it to the console, I only see [object Object] instead of the actual object types. console.log(`%c ${args[args.length-1]} ${performance['now'](true, args[args.length-1])} [(${args.slice(0, args.leng ...

Is it possible to implement a single lightbox modal that can display multiple images?

I am looking to create a fullscreen lightbox modal for multiple images, but I have been facing issues with finding the right solution. Most lightbox modals out there rely on jQuery and older versions of Bootstrap. Here is what I have tried so far: HTML: ...

Loop through each item in an array

Currently, I am leveraging vue.js and lodash to iterate through a list of events in order to extract the promoted events. My goal is to then store each event in a new object or array that holds a refined list of promoted events. However, instead of conso ...

Protractor's browser.wait function is not functioning properly when conducting tests on a non-AngularJS website

I am currently working on testing a non-angular JS website using Protractor. Even though my test case passes successfully, I am looking to eliminate the sleep statement and replace it with either a wait or Expected condition in my test case. Here is a sni ...

Ways to determine if an element has exceeded its container's boundaries

After creating the codesandbox, I have developed a webapp that heavily relies on user input. To keep it simple for demonstration purposes, I am displaying various authors on an A4 formatted page using `page` and `font-size` with the `vw` unit for responsiv ...

Connect to the MongoDB database running on localhost using the mongoose library

I am currently learning about the MEAN stack through this helpful tutorial. However, the tutorial assumes a connection to a remote mongodb installation. I have MongoDB already set up and running on my CentOS7 localhost. To modify the mongoose connect line ...

Using AJAX POST requests with PHP and SQL queries seems to function properly but unfortunately, it only

I am facing an issue with deleting an item from a list using AJAX, PHP, and MySQL. The first time I try to delete an item, the AJAX request works perfectly. However, on subsequent attempts, although the AJAX request returns success, the item is not deleted ...

changing an array into JSON format within the Laravel framework

My array looks like this: array:1 [▼ 0 => array:4 [▼ 0 => "2019-11-23" 1 => 5 2 => 5 3 => 5 I am trying to convert it to something similar to this (excluding the user information): Collection {#940 ▼ #ite ...

Facebook's Thumbs Down to My Code

I've been struggling to integrate a Facebook Like button on my blog using the following code: $("#fblike").append(" <iframe src='http://www.facebook.com/plugins/like.php?app_id=217624258276389&amp;" + window.location.href + "&amp;send ...

Python script for converting log.txt file to JSON

Currently in the process of learning Python with a limited programming background, I have taken on a challenging project. The task at hand involves converting a system log stored in a .txt file into JSON format. The ultimate goal is to create a Python pro ...

Error encountered when trying to access a 2D array passed as an argument to a function caused a

I have been using Code:Block for my programming. After compiling the code below (without any errors), I encountered a segmentation fault while running it. void print(int size, int **a) { for(int i=0;i<size;i++) { for(int j=0;j<size; ...

Dealing with a windows-1250 URI within a node.js/express framework

My application relies on a web service to generate its URIs, which sometimes results in a (potentially) windows-1250 encoded string (/punk%92d). Unfortunately, Express encounters an error: Connect 400 Error: Failed to decode param 'punk%92d' ...

Exploring the concepts of function referencing and prototypical inheritance in relation to function scopes

Consider the scenario where there are two distinct directives: angular.module('demo').directive('functional', [function (){ var idempotentMethods = ['idempotentMethod', 'otherIdempotentMethod']; return { res ...

Receiving an invalid date parsing value result

Having some trouble parsing a date in Angular with the following code snippet: $scope.startDate = '2016-12-16 15:11:52' $start = Date.parse($filter('date')($scope.startDate,'dd-MM-yyyy')); Unfortunately, the value returned i ...