JS - filter

by Alejandro M

JavaScript

//uso 1
// Define a callback function.
function CheckIfPrime(value, index, ar) {
    high = Math.floor(Math.sqrt(value)) + 1;

    for (var div = 2; div <= high; div++) {
        if (value % div == 0) {
            return false;
        }
    } 
    return true;
}

// Create the original array.
var numbers = [31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53];

// Get the prime numbers that are in the original array. 
var primes = numbers.filter(CheckIfPrime);

document.write(primes + "</br>");
// Output: 31,37,41,43,47,53

//uso 2
// Create the original array.
var arr = [5, "element", 10, "the", true];

// Create an array that contains the string
// values that are in the original array.
var result = arr.filter(
    function (value) {
        return (typeof value === 'string');
    }
);

document.write(result+ "</br>");
// Output: element, the

//uso 3
var checkNumericRange = function(value) {
    if (typeof value !== 'number')
        return false;
    else 
        return value >= this.minimum && value <= this.maximum;
}

var numbers = [6, 12, "15", 16, "the", -12];

// The obj argument enables use of the this value
// within the callback function.
var obj = { minimum: 10, maximum: 20 }

var result = numbers.filter(checkNumericRange, obj);

document.write(result+ "</br>");
// Output: 12,16
//uso 4
// Define a callback function that returns true
// if the current array element follows a space
// or is the first character.
function CheckValue(value, index, ar) {
    if (index == 0)
        return true;
    else
        return ar[index - 1] === " ";
}

// Create a string.
var sentence = "The quick brown fox jumps over the lazy dog."; 

// Create an array that contains all characters that follow a space.
var subset = [].filter.call(sentence, CheckValue); 

// You can use this alternative syntax.
//var subset = Array.prototype.filter.call(sentence, CheckValue);

document.write(subset);
// Output: T,q,b,f,j,o,t,l,d