r/learnjavascript • • 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

58 comments sorted by

View all comments

Show parent comment

3

u/code_monkey_001 May 08 '26

Now do the same starting array [1,2,3,4,5] but call arr.pushByVal(6). For you to be right, it would output [1,2,3,4,5,6,6,6,6,6]. If I'm right, it will output [1,2,3,4,5]. You're just selecting test cases that are coincidentally working like you think.

0

u/woofmeowmeowwoof May 08 '26

it cant do that if 6 is not in the array

6

u/code_monkey_001 May 09 '26

[6] outputs [6]
[6,7,8] outputs [6,7,8]
[6,1,2,3,4,5] outputs [6,1,2,3,4,5]

You're so wrong you can't even understand a rational explanation of how you're wrong.

0

u/woofmeowmeowwoof May 08 '26

let arr = [1, 2, 3, 4, 5, 6];

arr.pushByVal(6);

arr

(11) [1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6]

0

u/woofmeowmeowwoof May 08 '26

but when 6 is there is works fine

0

u/woofmeowmeowwoof May 08 '26

let arr = [1, 2, 3, 4, 5, 6];

arr.pushByVal(5);

arr

(10) [1, 2, 3, 4, 5, 6, 5, 5, 5, 5]

0

u/woofmeowmeowwoof May 08 '26

get fked sir.