0

I have two string arrays in my typescript app:

public play: Array<string> = [];
public scene: Array<string> = ['gittare','saxsophone','drum'];

I want to push one element like 'gittare' to play array and remove it from scene element:

this.play.push('gittare');
console.log(this.play);
this.scene.splice(this.scene.indexOf('gittare'));
console.log(this.scene);

I expect in the console, I see the ['saxsophone','drum'], but it gives me [].

How can I fix it?

2
  • 1
    Read the documentation for splice. Note carefully the description of what happens when the second parameter is omitted. Also, this has nothing to do with TypeScript. It's pure JavaScript as it has existed since the turn of the century. Commented Dec 18, 2016 at 13:46
  • 3
    I'm voting to close this question as off-topic because it is explained clearly in readily-available documentation. Commented Dec 18, 2016 at 13:46

3 Answers 3

1

tell splice how many items to remove.

this.scene.splice(this.scene.indexOf('gittare'),1);
Sign up to request clarification or add additional context in comments.

Comments

1

Raw JS:

const fruits = ['Apple', 'Mango', 'Banana'];

console.log(fruits);

const index = fruits.indexOf('Mango');
if (index > -1) { 
  fruits.splice(index, 1);
}

// fruits = ['Apple', 'Banana']
console.log(fruits);

Using lodash:

install lodash at first and then use the following,

npm install lodash
import _ from 'lodash';

const removed = _.remove(fruits, (n)=> n==='Mango');
 
console.log(fruits);
// => ['Apple', 'Banana']
 
console.log(removed);
// => ['Mango']

See lodash documentation https://lodash.com/docs/4.17.15#remove

4 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
Why use lodash ?
lodash is js utility library and is easier. lodash provides a number of functions to manage js easily.
0

Just update

this.scene.splice(this.scene.indexOf('gittare'));

to

this.scene.splice(this.scene.indexOf('gittare'), 1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.