Home > Net >  Any good way to add elements to a list if It’s satisfied with some conditions?
Any good way to add elements to a list if It’s satisfied with some conditions?

Time:09-13

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, {});
    });
  };

CodePudding user response:

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' }
];

CodePudding user response:

  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>

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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);

CodePudding user response:

Just use Array.prototype.filter, according to the documentation:

The filter() method creates and returns a new array containing all the elements of the original array that meet a condition determined by the callback function.

const numbers = [1,2,3,4,5,6,7,8,9,10] 
const evenNumbers = numbers.filter(n => n % 2 === 0);  
console.info(evenNumbers) // [2,4,6,8,10]
  • Related