Search code examples
javascriptarraysnode.jsactions-on-google

Array.splice() results in the value 'undefined'


Currently, i'm working on code which should remove the picked option of a user from a list. When I use the .splice() method it results in the value undefined.

Initially I thought it was an async problem, so I added async code for this.

app.intent("Optionpicker", (conv, input) => {
  conv.data.list = ['optionA', 'optionB', 'optionC', 'optionD']

  let choice = conv.parameters.choice

  async function listremover() {
    let index = conv.data.list.indexOf(choice);
    if (index > -1) {
      conv.data.list = conv.data.list.splice(index, 1);

      return conv.data.list
    }
  }
  listremover().then()

  conv.add(`Ok, your choice is ${choice}. The remaining options are: ${conv.data.list[0]}, ${conv.data.list[1]} and ${conv.data.list[2]}. Which one is next?`)
})

My expected result is the function returns an array without the chosen option of the user. At this moment, the value is 'undefined' and crshes the code.


Solution

  • I had to hard code a few values and remove your app.intent("Optionpicker", (conv, input) => { because app, conv, and input are undefined in this example.

    let conv = {};
    //let choice = 2; // conv.parameters.choice;
    // had to hard code values b/c app and conv are undefined in this example
    conv.data = {};
    conv.data.list = ['optionA', 'optionB', 'optionC', 'optionD'];
    let selected = {};
    
    async function listremover() {
      let index = conv.data.list.indexOf('optionB');
      //if (index > -1) {
      //conv.data.list = conv.data.list.splice(index, 1);
      //return conv.data.list;
      //}
    
      if (index > -1) {
        selected = conv.data.list.splice(index, 1);
        //return selected; // returns selected array
      }
      return conv.data.list; // returns remaining values of original array
    }
    
    listremover().then(function(res) {
      // removed `conv.add()` not sure where this is defined...
      //console.log(`Ok, your choice is ${selected}. The remaining options are: ${conv.data.list[0]}, ${conv.data.list[1]} and ${conv.data.list[2]}. Which one is next?`);
      console.log(res);
    });