Filter matching and unspecified values

JavaScript, Array · Oct 22, 2020

Filters an array of objects based on a condition while also filtering out unspecified keys.

const reducedFilter = (data, keys, fn) =>
  data.filter(fn).map(el =>
    keys.reduce((acc, key) => {
      acc[key] = el[key];
      return acc;
    }, {})
  );
const data = [
  {
    id: 1,
    name: 'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];
reducedFilter(data, ['id', 'name'], item => item.age > 24);
// [{ id: 2, name: 'mike'}]

More like this

  • Pull matching values from array

    Mutates the original array to filter out the values specified. Returns the removed elements.

    JavaScript, Array · Oct 22, 2020

  • Reject non-matching values

    Filters an array's values based on a predicate function, returning only values for which the predicate function returns false.

    JavaScript, Array · Oct 22, 2020

  • Pull values from array based on function

    Mutates the original array to filter out the values specified, based on a given iterator function.

    JavaScript, Array · Oct 22, 2020