Skip to content
Advertisement

Getting the previous value and updating n+1 item

I have an array of sequences, what i am trying to achieve is whichever last object completed property is true, then the next to next object will have is_to_happen as true

input

const sequences = [
    {
        "title": "Order placed",
        "completed": true
    },
    {
        "title": "To be confirmed",
        "completed": false
    },
    {
        "title": "Approx Thursday product will be shipped",
        "completed": false
    }
]

And this is what i want to have as an expected output

const output = [
    {
        "title": "Order placed",
        "completed": true,
        "is_to_happen": false
    },
    {
        "title": "To be confirmed",
        "completed": false,
        "is_to_happen": false
    },
    {
        "title": "Approx Thursday product will be shipped",
        "completed": false,
        "is_to_happen": true
    }
]

What i have tried so far using array.reduce is not working

sequences.reduce((acc,curr) => {
    acc = [...acc, curr]
    if(curr.completed){
     acc = [...acc, {...curr, is_to_happen: true}]
    }
    return acc     
}, [])

Advertisement

Answer

Usea reduce, and also keep track of the index of the completed item:

const sequences = [
    {
        "title": "Order placed",
        "completed": true
    },
    {
        "title": "To be confirmed",
        "completed": false
    },
    {
        "title": "Approx Thursday product will be shipped",
        "completed": false
    },
    { "title": "One more step", "completed": false }
]

const result = sequences.reduce ( (acc,item, i) => {
  if(item.completed) acc.completedIndex = i;
  acc.items.push( {...item,"is_to_happen": (acc.completedIndex != -1) && (i >= acc.completedIndex+2) } );
  return acc;
},{items:[], completedIndex:-1});

console.log(result.items);

Another way to achieve the same is to look backwards 2 elements in the original array for the completed flag

const sequences = [
    {
        "title": "Order placed",
        "completed": true
    },
    {
        "title": "To be confirmed",
        "completed": false
    },
    {
        "title": "Approx Thursday product will be shipped",
        "completed": false
    }
]

const result = sequences.map ( (item, i) => {
  return {...item, is_to_happen: !!sequences[i-2]?.completed};
});

console.log(result);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement