skip to Main Content

I have one array with the current week like:

[
 {time: "Monday", value: 0},
 {time: "Tuesday", value: 0},
 {time: "Wednesday", value: 0},
 {time: "Thursday", value: 0},
 {time: "Friday", value: 0},
 {time: "Saturday", value: 0},
 {time: "Sunday", value: 0}
]

and another array with the current values from this week, e.g. for wednesday:

[
 {time: "Monday", value: 5},
 {time: "Tuesday", value: 10},
]

My Problem now is that I don’t know how to replace the two objects from the second array into the first array so that I have a result like this:

[
 {time: "Monday", value: 5},
 {time: "Tuesday", value: 10},
 {time: "Wednesday", value: 0},
 {time: "Thursday", value: 0},
 {time: "Friday", value: 0},
 {time: "Saturday", value: 0},
 {time: "Sunday", value: 0}
]

2

Answers


  1. Chosen as BEST ANSWER

    I found a working solution for me:

    const arr3 = arr1.concat(arr2.slice(arr1.length));
    

  2. You can achieve this by looping thru defaultValues and for each element it checks if there is a corresponding value in the currentValues array, if found then it replaces the value, otherwise it keeps the original value

    const defaultValues = [
      { time: "Monday", value: 0 },
      { time: "Tuesday", value: 0 },
      { time: "Wednesday", value: 0 },
      { time: "Thursday", value: 0 },
      { time: "Friday", value: 0 },
      { time: "Saturday", value: 0 },
      { time: "Sunday", value: 0 }
    ];
    
    const currentValues = [
      { time: "Monday", value: 5 },
      { time: "Tuesday", value: 10 },
    ];
    
    const result = defaultValues.map((day) => {
      const currentValue = currentValues.find((item) => item.time === day.time);
      return currentValue ? currentValue : day;
    });
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search