w3resource

JavaScript: Remove elements from an array for which the given function returns false

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

Write a JavaScript program to remove elements from an array for which the given function returns false.

  • Use Array.prototype.filter() to find array elements that return truthy values.
  • Use Array.prototype.reduce() to remove elements using Array.prototype.splice().
  • The callback function is invoked with three arguments (value, index, array).

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const remove = (arr, func) =>
  Array.isArray(arr)
    ? arr.filter(func).reduce((acc, val) => {
        arr.splice(arr.indexOf(val), 1);
        return acc.concat(val);
      }, [])
    : [];

console.log(remove([1, 2, 3, 4], n => n % 2 === 0));

Sample Output:

[2,4]

Flowchart:

flowchart: Remove elements from an array for which the given function returns false.

Live Demo:

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


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get n random elements at unique keys from array up to the size of array.
Next: Write a JavaScript program to log the name of a function.

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.