0

I have the following array

myArray = ["zell", "allen", 34, 223344, age , "Stree 45"]

i need to delete every position which be length less than 4

in this case the position 2 and 4

I wrote

    for(var i=0; i<myArray.length; i++){
        if(myArray[i].trim().length<3){
        myArray.splice(i,1); 
        }
    }

but works only with the first one, I need with every one

thanks

ziggy12
  • 3
  • 3
  • 1
    what is `data`? I guess you meant `myArray`? You should start from the end, as each time you modify the array, you change what your for loop should be doing as you're shifting left the other values, but won't process them and will try to read past the end of the array... – B. Go Oct 03 '19 at 22:36
  • yes, sorry, fixed – ziggy12 Oct 03 '19 at 22:40
  • I can't see this working at all, since `34` is a Number, which does not have a `trim` method, so you would find you have an exception, and nothing has changed – Bravo Oct 03 '19 at 22:50
  • Also, the answer depends on one other point. Do you want to mutate `myArray` in place, in which case you would use splice, but you would iterate from the last item to the first; or, if can you assign a new array to `myArray`, you would use `filter` method – Bravo Oct 03 '19 at 22:51

1 Answers1

0

You can filter out the items that are shorter then 4 chars:

var myArray = ["zell", "allen", 34, 223344, "age" , "Stree 45"];
var filteredArr = myArray.filter(item => item.toString().length >= 4);
console.log(filteredArr);
Alon Yampolski
  • 851
  • 7
  • 15