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

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 
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
  }
];

console.log(reducedFilter(data, ['id', 'name'], item => item.age > 24));

Sample 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.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to create an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).
Next: Write a JavaScript program to hash an given input string into a whole number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Chunks an array into n smaller arrays

Example:

const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4)); 

Output:

[[1,2],[3,4],[5,6],[7,8]]