I have a simple case of pushing unique values into array. It looks like this:
this.items = []; add(item) { if(this.items.indexOf(item) > -1) { this.items.push(item); console.log(this.items); } }
Seems pretty straight-forward, right? No, as it appears. It doesn't add any values. I am sure it's some kind of silly mistake on my side, but I can't seem to find it.
push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.
Step 1 − Declare an array and input the array elements at run time. Step 2 − Start traversing the array and check, if the current element is already present in an array or not. Step 3 − If it is already present in an array then, move to the next element in an array and continue.
Yep, it's a small mistake.
if(this.items.indexOf(item) === -1) { this.items.push(item); console.log(this.items); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With