Here is the code implementation I am working with:
Array.prototype.abc = function(condition, t){
var arr = [];
for( var i = 0; i < this.length; i++){
arr.push(condition(this[i],t));
}
return arr;
};
var a = [1,2,3,4];
var t = 2;
alert(a.abc( function(item,diviser){
if(item % diviser === 0) { return item; }
},t));
My expected result should be [2,4]
. However, I am getting [,2,,4]
.
I attempted different conditions to prevent empty values in the array like below:
if(condition(this[i],t) !== false){ arr.push(condition(this[i],t)); }
I tried returning false
or true
from the else part when I perform the check on items. Interestingly, no matter what value I return, I still end up with blank sections in the array. Even without using the else
part, blank spaces persist. I am aware that I can use splice
to remove these blanks, but I am puzzled as to why they are being created in the first place. How can I avoid these blank elements in my array?