-1

Now I have an array like below.

  const reserveList = [
    { name: 'john', start: '2022-09-01' },
    { name: 'mark', start: '2022-09-02' },
    { name: 'ken', start: '2022-09-03' },
    { name: 'sara', start: '2022-09-05' },
  ];

and I want to add empty object if there is empty day between two days like below.

  const reserveList = [
    { name: 'john', start: '2022-09-01' },
    { name: 'mark', start: '2022-09-02' },
    { name: 'ken', start: '2022-09-03' },
    {},
    { name: 'sara', start: '2022-09-05' },
  ];

here is my code(it doesn't work). Is it possible to make it work using map or other ways?

  const newList = (reserveList: Array<any>) => {
    reserveList.map((reserve, index) => {
      dayjs(reserveList[index + 1].start).diff(
        dayjs(reserveList[index].start, 'day') > 1
      ) && reserveList.splice(index + 1, 0, {});
    });
  };
General Grievance
  • 4,555
  • 31
  • 31
  • 45
tehoo
  • 81
  • 2
  • 9

5 Answers5

2

Below examples mutate the reserveList in place.

Vanilla JS:

let i = 0;
while(true)
{
    let currStartDate = new Date(reserveList[i].start)
    let currEndDate = new Date(reserveList[i+1].start)
    let currDaysDiff = (currEndDate.getTime() - currStartDate.getTime()) / (1000 * 3600 * 24);
    
    if(currDaysDiff > 1) {
        let currFlag = 0;
        while(currDaysDiff > 1) {
            reserveList.splice(i + 1 + currFlag, 0, {})
            currDaysDiff--;
            currFlag++;
        }
    }
    
    i++;
    if(i === reserveList.length - 1)
        break;
}

Day.js:

let i = 0;
while(true)
{
    let currStartDate = dayjs(reserveList[i].start)
    let currEndDate = dayjs(reserveList[i+1].start)
    let currDaysDiff = currEndDate.dayjs(currStartDate, 'day')
    
    if(currDaysDiff > 1) {
        let currFlag = 0;
        while(currDaysDiff > 1) {
            reserveList.splice(i + 1 + currFlag, 0, {})
            currDaysDiff--;
            currFlag++;
        }
    }
    
    i++;
    if(i === reserveList.length - 1)
        break;
}  

You can try it with a more complicated array:

const reserveList = [
    { name: 'john', start: '2022-09-01' },
    { name: 'mark', start: '2022-09-06' },
    { name: 'ken', start: '2022-09-09' },
    { name: 'sara', start: '2022-09-11' }
];  

Result:

[
    { name: 'john', start: '2022-09-01' },
    {},
    {},
    {},
    {},
    { name: 'mark', start: '2022-09-06' },
    {},
    {},
    { name: 'ken', start: '2022-09-09' },
    {},
    { name: 'sara', start: '2022-09-11' }
];
Ergis
  • 1,105
  • 1
  • 7
  • 18
1

You can use the reduce function to go through the items in the original array, and add them to a new array while also injecting empty objects if the dates differ by more than one day (86400000 milliseconds)

const reserveList = [
  { name: "john", start: "2022-09-01" },
  { name: "mark", start: "2022-09-02" },
  { name: "ken", start: "2022-09-03" },
  { name: "sara", start: "2022-09-05" },
];

const oneSecond = 1000;
const oneDay = oneSecond * 60 * 60 * 24;

const newReserveList = reserveList.reduce(
  (newArr, currentItem, currentIndex) => {
    if (currentIndex !== 0) {
      const previousObject = reserveList[currentIndex - 1];
      const previousStart = new Date(previousObject.start);
      const currentStart = new Date(currentItem.start);

      const diff = Math.abs(previousStart.getTime() - currentStart.getTime());

      if (diff > oneDay) {
        newArr.push({});
      }
    }

    newArr.push(currentItem);

    return newArr;
  },

  // Initialize the 'newArr' value to be an empty array
  []
);


console.log(newReserveList)
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
  • @Ergis OP's answer to the comments was ambiguous. If that is the case then the modification is easy and is left as an exercise for OP – Abir Taheer Sep 13 '22 at 08:43
1
  1. You can reduce method instead of map, because map is desigened to manipulate each item not add or delete items from the array.

  2. The days.js condition is wrong, this is the correct syntax.

dayjs(reserveList[index + 1].start).diff( 
    reserveList[index].start, "day"
)> 1

const reserveList = [
    { name: "john", start: "2022-09-01" },
    { name: "mark", start: "2022-09-02" },
    { name: "ken", start: "2022-09-03" },
    { name: "sara", start: "2022-09-05" },
];
const newList = (reserveList) => {
    return reserveList.reduce((acc, reserve, index) => {
        let dayDifference
        if (reserveList[index + 1]) {
            dayDifference = dayjs(reserveList[index + 1].start).diff(
                reserveList[index].start, "day"
            ) > 1;
        }
        dayDifference ? acc.push(reserve, {}) : acc.push(reserve);
        return acc;
    }, []);
};
console.log(newList(reserveList))
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/dayjs.min.js" integrity="sha512-Ot7ArUEhJDU0cwoBNNnWe487kjL5wAOsIYig8llY/l0P2TUFwgsAHVmrZMHsT8NGo+HwkjTJsNErS6QqIkBxDw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

With one line function

const reserveList = [
    { name: "john", start: "2022-09-01" },
    { name: "mark", start: "2022-09-02" },
    { name: "ken", start: "2022-09-03" },
    { name: "sara", start: "2022-09-05" },
];
const newList = (reserveList) => reserveList.reduce((acc, reserve, index) => [...acc, reserve, ...((reserveList[index + 1] ? (dayDifference = dayjs(reserveList[index + 1].start).diff(reserveList[index].start, "day") > 1) : null) ? [{}] : []),],[]);

console.log(newList(reserveList));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.5/dayjs.min.js" integrity="sha512-Ot7ArUEhJDU0cwoBNNnWe487kjL5wAOsIYig8llY/l0P2TUFwgsAHVmrZMHsT8NGo+HwkjTJsNErS6QqIkBxDw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Mina
  • 14,386
  • 3
  • 13
  • 26
1

add one empty object per any one diff days:

 const reserveList = [
    { name: 'john', start: '2022-09-01' },
    { name: 'mark', start: '2022-09-02' },
    { name: 'ken', start: '2022-09-03' },
    { name: 'sara', start: '2022-09-07' },
  ];

const newList = [];

 reserveList.reduce((previousValue, currentValue, index) => {
  if (index !== 0) {
      const diffDays = +currentValue.start.split('-')[2] - +reserveList[index - 1].start.split('-')[2];
      if (diffDays > 1) {
        [...Array(diffDays - 1)].forEach((item) => {
          newList.push({})
        });
      }
     }
     newList.push(currentValue)
     return previousValue
   },[]);


console.log(newList)

playground

Arman Ashoori
  • 265
  • 1
  • 8
0

This might Work !

const dayjs = require("dayjs");
const reserveList = [
  { name: "john", start: "2022-09-01" },
  { name: "mark", start: "2022-09-02" },
  { name: "ken", start: "2022-09-03" },
  { name: "sara", start: "2022-09-05" },
  { name: "amir", start: "2022-09-10" },
  { name: "Masood", start: "2022-09-13" },
];

const newList = () => {
  let editedList = [];
  for (let index in reserveList) {
    editedList.push(reserveList[parseInt(index)]);
    if (parseInt(index) <= reserveList.length - 2) {
      console.log(
        reserveList[parseInt(index) + 1].start,
        reserveList[parseInt(index)].start
      );

      let diffVal = dayjs(reserveList[parseInt(index) + 1].start).diff(
        reserveList[index].start,
        "d"
      );
      console.log(diffVal);

      if (diffVal > 1) {
        for (let j = 1; j < diffVal; j++) {
          editedList.push({});
        }
      }
    }

  }
  return editedList;
};
let editedlist = newList();
console.log(reserveList);
console.log(editedlist);

Masood
  • 21
  • 4