Web Develop Wolf
Web Develop Wolf

Reputation: 6326

Removing an object from an array without knowing the index

I need to remove an element from an array used the splice method, but I don't know the index of the object that I wish to remove. I've tried adding an ID that mimicks the index to remove the item but this doesn't appear to be working.

RandomiseNextQuestion: function(player1qs) {

    // Pick a random question
    this.Questions = player1qs;
    var rand = Math.floor(Math.random() * player1qs.length);
    function findQ(q) { 
        return q.qId === rand;
    }

    this.CurrentQuestion = player1qs.find(findQ);

    if(this.CurrentQuestion) {
        // Process question
    }

    // Remove that question so it can't be used again
    this.Questions.splice(this.CurrentQuestion.qId, 1);
}

I've also tried using the 'rand' value to remove the item but that doesn't work either.

Upvotes: 0

Views: 2555

Answers (2)

Arno_Geismar
Arno_Geismar

Reputation: 2330

You can map to find the index of your element

var yourArray = ['bla','bloe','blie'];

var elementPos = yourArray.indexOf('bloe');
console.log(elementPos); // this will show the index of the element you want

yourArray.splice(elementPos,1); // this wil remove the element 

console.log(yourArray);

you can do it like this I suppose

getRandomQuestion: function(playerQuestions) {
    // Pick a random question and return question and index of question
    this.questions = playerQuestions;
    var rand = Math.floor(Math.random() * playerQuestions.length);
    return this.questions[rand];
}

removeQuestion: function(question, playerQuestions){
       playerQuestions.splice(playerQuestions.indexOf(question), 1);
       return playerQuestions; // removes question and gives back the remaining questions
}

processQuestion: function(question){
//do something with the question
}

// you would call it like this
var questionsPlayer1 = ["the meaning of life", "the answer to everything"]
var question = getRandomQuestion(questionsPlayer1);
processQuestion(question);
removeQuestion(question, questionsPlayer1);

Upvotes: 1

zurfyx
zurfyx

Reputation: 32797

All you can do with a single command is a filter

arr.filter((value) => value !== removeValue)

Otherwise, if you want to keep using your array (aka mutable), you will have to use something like:

const i = arr.indexOf('value')
arr.splice(i, 1)

Upvotes: 1

Related Questions