DEV Community

Discussion on: The case for DRY code

Collapse
 
kalashin1 profile image
Kinanee Samson • Edited

I see, this wouldn't be the final solution, and if indexOf returns partial matches, you can use array.find() instead.

function findOrderByAddressField(field) {
    let foundOrders = []
    let foundOrder;
    orders.forEach(order => {
      foundOrder = Object.values(order.address).find(v => v === field)
     foundOrders.push(foundOrder)
    })
    return foundOrders
}

const riversOrders = findOrderByAddressField('rivers') // find order by state
const phOrders = findOrderByAddressField('port harcourt') // find orders by city
const NigerianOrders = findOrderByAddressField('nigeria') // find orders by country
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grahamthedev profile image
GrahamTheDev • Edited

You still have the issue of matching across all fields in the above example, so a search for "rivers" would match on state, city and country.

Collisions would be rare but if this was something else like names with first name and surname fields, you could search for "Frank" and it would match "Frank Johnson" and "John Frank".

The code I wrote was to mirror your original functions where each one was for a specific field but your function is ideal for if you want to search across all 3 fields at once, it just doesn't do the same as the first functions so isn't ideal as a comparison.

Obviously it all depends on what the end use case is!