Search code examples
javascriptarraysloopsfor-looplodash

Concat two arrays with filtering


I have two arrays. I need to combine both of them and make a new array which has dayOfWeek 2, 3, 4, 5, 6. Which means priority for the dayOfWeek is in array1. Means need to keep dayOfWeek 3, 4, 5 from array1.

array1 = [
  {dayOfWeek: 2, home1: "01:30"},
  {dayOfWeek: 3, home1: "02:30"},
  {dayOfWeek: 4, home1: "03:30"},
  {dayOfWeek: 5, home1: "04:30"},
]

array2 = [
  {dayOfWeek: 3, home1: "05:30"},
  {dayOfWeek: 4, home1: "06:30"},
  {dayOfWeek: 5, home1: "07:30"},
  {dayOfWeek: 6, home1: "08:30"},
]

Output should be

finalArray = [
  {dayOfWeek: 2, home1: "01:30"},
  {dayOfWeek: 3, home1: "02:30"},
  {dayOfWeek: 4, home1: "03:30"},
  {dayOfWeek: 5, home1: "04:30"},
  {dayOfWeek: 6, home1: "08:30"},
]

I tried this but it pushes the dayOfWeek from both the arrays. How can I filter them?

const finalArray = []
array1.map((a) => {
    array2.map((a2) => {
        if (a.dayOfWeek === a2.dayOfWeek) {
          finalArray.push(a)
        }
        if (a.dayOfWeek === a2.dayOfWeek) {
          finalArray.push(a2)
        }
    })
})

Thanks in advance!!!


Solution

  • Use lodash's _.unionBy(). The predominant array should be the 1st array passed to the function.

    const array1 = [{"dayOfWeek":2,"home1":"01:30"},{"dayOfWeek":3,"home1":"02:30"},{"dayOfWeek":4,"home1":"03:30"},{"dayOfWeek":5,"home1":"04:30"}]
    const array2 = [{"dayOfWeek":3,"home1":"05:30"},{"dayOfWeek":4,"home1":"06:30"},{"dayOfWeek":5,"home1":"07:30"},{"dayOfWeek":6,"home1":"08:30"}]
    
    const result = _.unionBy(array1, array2, 'dayOfWeek')
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    If you need to combine several properties to use as the union value, you can use:

    _.unionBy(array1, array2, o => `${o.id}-${o.dayOfWeek}`)