-2

I want to join two arrays by id but with different amount of elements, Does any suggestions?

Thanks

Array 1

soccer = [{id: 1, name: 'Munich'}, {id: 2, name: 'Dortmund'}]

Array 2

points = [{id: 2, value: 40}]

Result

result = [{id: 1, name: 'Munich'}, {id: 2, name: 'Dortmund', value: 40}]

My attempt was

teams.map((item,i)=>{
    if(item.id === points[i].id){
      return Object.assign({},item, points[i])
    }
})

enter image description here

lyonTypescript
  • 125
  • 1
  • 3
  • 10
  • is there any case that the array 2 will contain 1 item with id:3? And do you want that to be in result array? – Alex - Tin Le Mar 24 '20 at 17:43
  • You can copy and paste from the console, you know. No need to use images, which are unreadable by screen readers and search engines... – Heretic Monkey Mar 24 '20 at 17:43
  • 1
    `teams` in your attempt should be `soccer`? If so then there are more elements in `soccer`/`team` as in `points` but you try to access the elements in `points` with the index of `teams`/`soccer` – Andreas Mar 24 '20 at 17:44
  • Your `.map()` should always return an element. Right now you would only return the matching object/team. – Andreas Mar 24 '20 at 17:45

1 Answers1

1

This should works:

soccer.map(item => ({...item, ...points.find(({id}) => id === item.id)}))

It basically map the soccer array with both the props of the items in soccer and points array, using the id as key. Notice that given the order, if there are namesake props in both arrays, the points one wins (since it's the latter to be added).

ZER0
  • 24,846
  • 5
  • 51
  • 54