Search code examples
javascriptarrayslodash

Replace array of objects


I have below array of objects

const array = [
   { home1: "05:45", dayOfWeek: 1, away: "09:30"},
   { home1: "05:15", dayOfWeek: 2, away: "09:30"},
   { home1: "17:30", dayOfWeek: 5, away: "09:30"},
   { home1: "16:30", dayOfWeek: 7, away: "09:30"}
]

I have four dayOfWeek (1,2,5,7). Now I need to push the remaining three (3,4,6) with the dummy object ({ home1: "05:30", dayOfWeek: 7, away: "09:30"})

Now the logical part is I don't know which dayOfWeek are present in the array. There may be only one, two, three or blank. I need to push 7 days in that array every time.

How this can be done? Please suggest me the best way

Thank you!!!


Solution

  • One option would be to make a Set of the days contained in the array so far, then iterate from 1 to 7, pushing a new object to the array with that day if it's not contained in the set:

    const array = [
       { home1: "05:45", dayOfWeek: 1, away: "09:30"},
       { home1: "05:15", dayOfWeek: 2, away: "09:30"},
       { home1: "17:30", dayOfWeek: 5, away: "09:30"},
       { home1: "16:30", dayOfWeek: 7, away: "09:30"}
    ];
    const dummy = { home1: "05:30", away: "09:30" };
    const days = new Set(array.map(({ dayOfWeek }) => dayOfWeek));
    for (let i = 1; i <= 7; i++) {
      if (!days.has(i)) array.push({ ...dummy, dayOfWeek: i });
    }
    console.log(array);

    I used a Set to reduce complexity, but I suppose if you only ever need 7 objects, it doesn't matter much, you could use find instead without creating a collection beforehand

    const array = [
       { home1: "05:45", dayOfWeek: 1, away: "09:30"},
       { home1: "05:15", dayOfWeek: 2, away: "09:30"},
       { home1: "17:30", dayOfWeek: 5, away: "09:30"},
       { home1: "16:30", dayOfWeek: 7, away: "09:30"}
    ];
    const dummy = { home1: "05:30", away: "09:30" };
    for (let i = 1; i <= 7; i++) {
      if (!array.find(({ dayOfWeek }) => dayOfWeek === i)) {
        array.push({ ...dummy, dayOfWeek: i });
      }
    }
    console.log(array);