w3resource

JavaScript : Filter an array of objects based on a condition while also filtering out unspecified keys

JavaScript fundamental (ES6 Syntax): Exercise-98 with Solution

Filter Array of Objects by Condition

Write a JavaScript program to filter an array of objects based on a condition while also filtering out unspecified keys.

  • Use Array.prototype.filter() to filter the array based on the predicate fn so that it returns the objects for which the condition returned a truthy value.
  • On the filtered array, use Array.prototype.map() to return the new object.
  • Use Array.prototype.reduce() to filter out the keys which were not supplied as the keys argument.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define the 'reducedFilter' function to filter an array of objects and return a new array of objects containing only selected keys based on a filtering function.
const reducedFilter = (data, keys, fn) =>
  // Filter the data array based on the filtering function 'fn', then map the filtered objects to return a new array of objects containing only selected keys.
  data.filter(fn).map(el =>
    // Reduce the selected keys for each object to build a new object containing only those selected keys.
    keys.reduce((acc, key) => {
      acc[key] = el[key];
      return acc;
    }, {})
  );

// Test the 'reducedFilter' function with sample data.
const data = [
  {
    id: 1,
    name: 'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];

console.log(reducedFilter(data, ['id', 'name'], item => item.age > 24)); // Output: [{ id: 2, name: 'mike' }]

Output:

[{"id":2,"name":"mike"}]

Flowchart:

flowchart: Filter an array of objects based on a condition while also filtering out unspecified keys

Live Demo:

See the Pen javascript-basic-exercise-98-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that filters an array of objects, returning only those that meet a specified condition.
  • Write a JavaScript function that iterates over an array of objects and omits properties that do not satisfy a given predicate.
  • Write a JavaScript program that applies a condition to each object in an array and returns a new array with the filtered results.

Go to:


PREV : Object from Truthy Function Keys.
NEXT : Hash String into Number.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.