How to push to array while iterating it

Viewed 30

My ratios array is very big and I just want to create a default '00' month for each item. Basically would be month 1,2,3,...,11,12 and then 00. THen another item 1,2,3.. , 11, 12, 00 and so on

let ratios = [{
  item: 'foo',
  ratio: 1,
  month: '11'
}, {
  item: 'foo',
  ratio: 1.5,
  month: '12'
}, {
  item: 'bar',
  ratio: 1.5,
  month: '01'
}];

console.log(ratios);

ratios.forEach(ratio => {
  if (ratio.month === '12') {
    ratios.push({
      item: ratio.item,
      ratio: 0.5, // hardcoded, doesn't matter
      month: '00'
    });
  }
});

console.log('Ratios with average: ' + JSON.stringify(ratios));

I want to push the month '00' after the '12' and then start over again 1,2... but it's pushing the 00 to the end of the array.

How can I achieve this?

PS: the console.log should be

[{"item":"foo","ratio":1,"month":"11"},{"item":"foo","ratio":1.5,"month":"12"}, {"item":"foo","ratio":0.5,"month":"00"},{"item":"bar","ratio":1.5,"month":"01"}]

PS: I want to push to a certain position of the array

0 Answers
Related