0

Origin Object is:

obj = { date: '2021-05-30', stock: 230, location_id: 'Bangalore' },
{ date: '2021-05-31', stock: 350, location_id: 'Bangalore' },
{ date: '2021-06-01', stock: 320, location_id: 'Bangalore' },
{ date: '2021-06-07', stock: 210, location_id: 'Bangalore' },
{ date: '2021-06-08', stock: 210, location_id: 'Bangalore' },
{ date: '2021-06-09', stock: 210, location_id: 'Bangalore' },
{ date: '2021-06-10', stock: 210, location_id: 'Bangalore' },
]
obj.reduce((m, o, i) => {
  var prev = m[i - 1];
  if (prev) {
    o.stock = o.stock + prev.stock;
  }
  m.push(o);
  return m;
}, []);

I tried above script but is updating current date itself. But I am getting following outcome:

0: {date: "2021-05-31", stock: 230, location_id: "Bangalore"}
1: {date: "2021-05-31", stock: 580, location_id: "Bangalore"}
2: {date: "2021-06-01", stock: 900, location_id: "Bangalore"}
3: {date: "2021-06-07", stock: 1110, location_id: "Bangalore"}
4: {date: "2021-06-08", stock: 1320, location_id: "Bangalore"}
5: {date: "2021-06-09", stock: 1530, location_id: "Bangalore"}
6: {date: "2021-06-10", stock: 1740, location_id: "Bangalore"}```

Expecting format is like

0: {date: "2021-05-30", stock: 0, location_id: "Bangalore"}
1: {date: "2021-05-31", stock: 230, location_id: "Bangalore"}
2: {date: "2021-06-01", stock: 580, location_id: "Bangalore"}
3: {date: "2021-06-07", stock: 900, location_id: "Bangalore"}
4: {date: "2021-06-08", stock: 1110, location_id: "Bangalore"}
5: {date: "2021-06-09", stock: 1320, location_id: "Bangalore"}
6: {date: "2021-06-10", stock: 1530, location_id: "Bangalore"}```

Please anyone provide the right solution is greatly appreciated!

1 Answer 1

1

const obj = [
  { date: '2021-05-30', stock: 230, location_id: 'Bangalore' },
  { date: '2021-05-31', stock: 350, location_id: 'Bangalore' },
  { date: '2021-06-01', stock: 320, location_id: 'Bangalore' },
  { date: '2021-06-07', stock: 210, location_id: 'Bangalore' },
  { date: '2021-06-08', stock: 210, location_id: 'Bangalore' },
  { date: '2021-06-09', stock: 210, location_id: 'Bangalore' },
  { date: '2021-06-10', stock: 210, location_id: 'Bangalore' },
]
obj.reduce((acc, cur) => { 
  const newAcc = acc + cur.stock; 
  cur.stock = acc; 
  return newAcc 
},0)
console.log(obj)

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

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.