0

I want to create an Array of objects in a messages constant which are 3 keys /values : author, hour and message

Problem : some object have a blank author value, and I want to get the previous iteration author key/value in the .map function itself to replace the blank value (current iteration)

Is it possible to get the previous iteration element in the .map function even if the iteration is not yet finished ?

Thanks a lot for your help

From this

0:
author: "Kara"
hour: "19:32"
message: "Salut Mia merci pour ton ajout cela va me servir de test !"
1:
author: ""
hour: ""
message: "Ceci est un test : message 2 !!" 

To this :


0:
author: "Kara"
hour: "19:32"
message: "Salut Mia merci pour ton ajout cela va me servir de test !"
1:
author: "Kara"
hour: "19:32"
message: "Ceci est un test : message 2 !!" 

I want to copy the previous iteration object values.

3 Answers 3

2

Is it possible to get the previous iteration element in the .map function even if the iteration is not yet finished ?

Yes. The second argument is the current index and the third argument is the array itself, so you can just access array[index - 1] inside the .map callback. That won't work for the first element though (as there is no previous element).

Sign up to request clarification or add additional context in comments.

1 Comment

A small code example might be handy - the asker might not even know that map gives its callback function index/array arguments.
1

You can use the index from the handler:

array.map((o, index, arr) => {
   let previous = arr[index - 1]; // For index === 0, the previous object will be undefined.
});

Go and read about it -> Array.prototype.map

Comments

0
array.map((ele, index, arr) => {
   let keys = Object.keys(ele);
   keys.each((key) => {
    if (ele[key] === '') {
     ele[key] = arr[index - 1][key];
    }
   });
   return ele;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.