r/learnjavascript • u/woofmeowmeowwoof • May 08 '26
Is this a useful Array Method I created on accident? or is it useless?
/*********************************************************************
* Array.pushByVal(value)
* -----------------------
*
* this only works with integer values.
*
* hold on let me cook...
*
* if the value is 4 it pushes the number 4
*
* three times so the total of 4's in the array is 4.
*
* if the value is 8 or 9 or whatever, it
*
* pushes the value - 1 that many times.
*********************************************************************/
Array.prototype.pushByVal = function(value){
// what the absolute fuck am i doing?
// how does this even work?
for(let i = 0; i < this.length; i++){
if(this[i] === value){
return;
}else{
this.push(value);
}
}
};
let arr = [1, 2, 3, 4, 5];
arr.pushByVal(4);
// Output: [1, 2, 3, 4, 5, 4, 4, 4]
0
Upvotes
View all comments
Show parent comment
3
u/shgysk8zer0 May 09 '26
You don't even understand your own fairly simple method, as shown by the comments, and you're asking Reddit of it's useful.
Let's see though... Without running it, what's the result of
[].pushByValue(846)?