Filtering Arrays in JavaScript

In this JavaScript tutorial, we will learn how we can filter data in JavaScript arrays and store the filtered values in a new javascript array.

let charlist = ["**","ab","cd","*","ef","*","gh","*"];

let newArray = charlist.filter(function(element) {
  return (element !== "*");

console.log(newArray); // ["ab", "cd", "ef", "gh"]

The filter() method is another ES6 cool addition, like forEach() and map(). Like them, the method is a way of applying a callback function to every array element. The function has three parameters: the array element, and, optionally, the index for the element and the original array.

The function passed as a parameter to the filter() method returns either true or false based on some test against the array elements. This returned value determines if the array element is added to a new array: it’s added if the function returns true; otherwise, it’s not added. In the solution, the character string (*) is filtered from the original array when the new array is created.

Leave a Reply

Your email address will not be published. Required fields are marked *