Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
Angular toggle item in array always removing first value from array and ignoring given value

I am trying to get a button click toggle a given value from an array.

So here is the array with all the values:

values = ['one', 'two', 'three', 'four'];

Here I execute the toggleTest method and pass string value of 'one'

<button (click)="toggleTest('one')"></button>

Finally here is should remove or add the value from the values array, depending if it exists or not.

toggleTest(value) {
   // if value exists in this.values then remove it ... else add it.
   So I tried this:

   if (this.values.includes(value)) {
      // it's there so lets remove it
      this.values.splice(value, 1);
   } else {
     // its not there so lets add it
     this.values.push(value, 1);
   }

}

When I try this it removes the first entry all the time and ignores the value given...it just removes one from the values array.

How can I fix this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The splice function takes an index as its first parameter, not the value itself (see here).

So you could replace this:

this.values.splice(value, 1);

with this:

let index = this.values.indexOf(value);
this.values.splice(index, 1);
about 4 years ago · Juan Pablo Isaza Report

0

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

The push() method adds one or more elements to the end of an array and returns the new length of the array.

toggleTest(val){

   if (this.values.includes(val)) {
      // it's there so lets remove it
     let index = this.values.indexOf(val);
     this.values.splice(index, 1);
   } else {
     // its not there so lets add it
     this.values.push(val);
   }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!