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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay