Shubham Shukla Shubham Shukla - 6 months ago 13
Javascript Question

some elements are not removed from array

i have created an array for vowels position in string now i want reomve all elements that have value -1 from this array but its not working

function translatePigLatin(str) {
var vowelp=[];
var newarr=str.split('');
vowelp.push(newarr.indexOf('a'));
vowelp.push(newarr.indexOf('e'));
vowelp.push(newarr.indexOf('i'));
vowelp.push(newarr.indexOf('o'));
vowelp.push(newarr.indexOf('u'));
var minvowel=vowelp[0];
for(var i=0;i<vowelp.length;i++) { //looping through vowel's position array
if(vowelp[i]==-1) {
vowelp.splice(i,1);
console.log(vowelp[i]);
}
}
return vowelp;
}


input-translatePigLatin("consonant");
output that i am getting is[6,-1,1] but i want [6,1]

Answer

Simple way is to use filter()

function translatePigLatin(str) {
  var vowelp = [];
  var newarr = str.split('');
  vowelp.push(newarr.indexOf('a'));
  vowelp.push(newarr.indexOf('e'));
  vowelp.push(newarr.indexOf('i'));
  vowelp.push(newarr.indexOf('o'));
  vowelp.push(newarr.indexOf('u'));
  var minvowel = vowelp[0];
  return vowelp.filter(function(v) {
    return v != -1;
  })
}

console.log(translatePigLatin("consonant"));


In your case you need to decrement the value of i in case of item removal otherwise it will skip the next element.

function translatePigLatin(str) {
  var vowelp = [];
  var newarr = str.split('');
  vowelp.push(newarr.indexOf('a'));
  vowelp.push(newarr.indexOf('e'));
  vowelp.push(newarr.indexOf('i'));
  vowelp.push(newarr.indexOf('o'));
  vowelp.push(newarr.indexOf('u'));
  var minvowel = vowelp[0];
  for (var i = 0; i < vowelp.length; i++) { //looping through vowel's position array
    if (vowelp[i] == -1) {
      vowelp.splice(i, 1);
      i--;
      console.log(vowelp[i]);
    }
  }
  return vowelp;
}

console.log(translatePigLatin("consonant"));


You can make it more simple

`function translatePigLatin(str) {

return ['a','e','i','o','u'].map(function(v){ return str.indexOf(v); }).filter(function(v){ return v!=-1; }); }`