JAVA SCRIPT - Creating a Filtered Array

Creating a Filtered Array


Problem

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

Solution

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"]


EXPLAIN 

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.

0 comments:

Post a Comment