1

I have two arrays of objects.

I am doing a comparison by id and availability

For example

   let newCars = []
   cars.forEach((car) => {        
      const element = _.find(this.state.cars, function(o) {
        return (o.id === car.id && (o.available < car.available))
      })
      if (element) {
        newCars.push(element)
      }    
    })

However, I would also like to include in the newCars array the elements that are not present in this.state.cars, but compared only by id.

For example, if cars has {id: 1, available: 4}, and this.state.cars has {id: 1, available: 5}, the would count as being present in both arrays and not be returned.

In summary, I need all the elements in cars for which car.available > car.available for the element with the same id in this.state.cars, plus, all the elements in cars which are not included in this.state.cars doing the comparison inclusion by id only.

Is this possible? (Uisng lodash or plain js)

Thank you

1 Answer 1

2

Try to find element, if not found add it, if found and has availability required also add it.

   let newCars = []
   cars.forEach((car) => {        
      const element = _.find(this.state.cars, function(o) {
        return o.id === car.id
      })
      if (!element || element.available < car.available) {
        newCars.push(car)
      }    
    })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.