I'm having trouble identifying the issue in my code. Despite reading numerous articles on slice
and splice
, I am unable to achieve the desired outcome in my Angular project (not using both methods simultaneously). The results are not as expected. Below is the snippet of my code:
Snippet with slice:
newArray:string[];
mutatedArray:string[];
removeOneFruit() {
this.newArray=['Apple', 'Orange', 'Plums', 'Grapes'];
console.log("Before slicing: "+this.newArray);
this.mutatedArray=this.newArray.slice(this.newArray.indexOf('Orange'),1);
console.log("After slicing: "+this.mutatedArray);
}
Output:
Before slicing: Apple,Orange,Plums,Grapes
After slicing:
The result after slicing is simply blank. No errors or warnings appear on the console. This behavior puzzles me.
Snippet with splice:
newArray:string[];
mutatedArray:string[];
removeOneFruit() {
this.newArray=['Apple', 'Orange', 'Plums', 'Grapes'];
console.log("Before splicing: "+this.newArray);
this.mutatedArray=this.newArray.splice(this.newArray.indexOf('Orange'),1);
console.log("After splicing: "+this.mutatedArray);
}
Output:
Before slicing: Apple,Orange,Plums,Grapes
After slicing: Orange
The obtained output is unexpected. I anticipate an array containing all fruits except for Orange
. Please advise accordingly.
PS: It's a simplified representation of a larger project where the items are not fruits and are not hardcoded either.