DEV Community

Cover image for Using filter() Array Method to Keep Targets in an Array
Calvin
Calvin

Posted on

Using filter() Array Method to Keep Targets in an Array

If you need to implement a function to remove all values from an array that are not the same as the target value you want to return, you can use the filter() Array method like this:



var filter = function (arr, target) {
  // Write your code below


 var equalTarget = arr.filter(function(number) {
  return number == target;
});




  return equalTarget ;
}

var numbers = [1, 3, 5, 7, 5, 3, 1];
var only3 = filter(numbers, 3);
console.log(only3);
// -> [3, 3]
console.log(numbers);
// -> [1, 3, 5, 7, 5, 3, 1]


Enter fullscreen mode Exit fullscreen mode

Top comments (0)