JAVA SCRIPT - Creating a Filtered Array

Creating a Filtered Array


You want to filter element values in an array and assign the results to a new array. 


Use the Array filter() method:

var charSet = ["**","bb","cd","**","cc","**","dd","**"];
var newArray = charSet.filter(function(element) {
 return (element !== "**");
console.log(newArray); // ["bb", "cd", "cc", "dd"]


The filter() method is another ECMAScript 5 addition, like forEach() and map() , Like them, the method is a way of applying a callback function to every array element. 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; other‐ wise, it’s not added. In the solution, the character string (**) is filtered from the original array when the new array is created. The function has three parameters: the array element, and, optionally, the index for the element and the original array.


Post a Comment