alex
alex

Reputation: 7601

Writing a simple find function without using some and every separately

I want to create a simple find function that finds an object in an array if the key in value matches one of its keys:

find(
  [ { name:'1', value:'a'}, { name:'2', value:'b' } ],
  { name:'1' }
) // => { name:'1', value:'a'}

If value has more than two keys then the object in the array has to match exactly:

find(
  [ { name:'1', value:'a'}, { name:'2', value:'b' } ],
  { name:'1', value:'b' }
) // => null

I know how to do this but by using some and every separately:

const keys = (object) => {
  return Object.keys(object)
}

const find = (array, value) => {
  return array.filter(object => {
    return keys(object).every(key => { // change this to .some
      return object[key] === value[key]
    })
  })[0]
}

Is there a way to write this without me having to swap every with some and vice versa?

Upvotes: 0

Views: 44

Answers (1)

Bergi
Bergi

Reputation: 664936

I think you want to swap object with value, not every with some:

function find(array, value) {
  return array.find(object =>
    Object.keys(value).every(key =>
//                     ^^^^^
      object[key] === value[key]
    )
  );
}

This will work for both your cases, as it tests for value to be a subset of the properties in the respective object.

Upvotes: 1

Related Questions