JavaScript filter and call methods

by lasha

JavaScript

// 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."; 
/////////var arrSentence = sentence.split("");

// Create an array that contains all characters that follow a space.
// The commented out statement shows an alternative syntax.
/////////var subset1 = arrSentence.filter(CheckValue);
var subset = [].filter.call(sentence, CheckValue); 

// Another way of showing how call works when chained with filter
//var subset = [].filter.call(sentence, function(value, index, ar) {
//    if (index == 0) {
//        return true;
//    } else {
//        return ar[index - 1] === " ";
//    }
//}); 

console.log(subset);
// var subset = Array.prototype.filter.call(sentence, CheckValue);
 
// Convert the result array to a string.
var result = subset.join("");
/////////var result = subset1.join("");

document.write(result);
// Output: Tqbfjotld