1

I'm a really beginner in javascript

I have an array containing

array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]

And I want another array but only with words that have length > 3

array_cleaned = ["quick","brown","jumped","lazy"]

How it is currently implemented:

array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]

array_clean = [];
for(var i=0; i<array_1.length; i++){
    if(array_1[i].length > 3) 
        array_clean.push(array_1[i]);
}

document.write(array_clean)

But I'm looking for a way to actually filter it. Any ideas?

falsarella
  • 12,217
  • 9
  • 69
  • 115
OWADVL
  • 10,704
  • 7
  • 55
  • 67
  • 1
    Please define "doesn't seem to work", since [your code seems to work](http://jsfiddle.net/d29b6zL3/). – Teemu Feb 27 '15 at 15:52

3 Answers3

9

You can use filter method:

const array_1 = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];

const new_array = array_1.filter((element) => {
  return element.length > 3;
});

// OR refactor
// const new_array = array_1.filter( (element) => element.length > 3);

console.log(new_array)

// Output:
// ["quick", "brown", "jumped", "over", "lazy"]
biberman
  • 5,606
  • 4
  • 11
  • 35
antyrat
  • 27,479
  • 9
  • 75
  • 76
4

You can filter it

var array_cleaned = array_1.filter(function(x) {
    return x.length > 3;
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

If you don't want to use the filter function, this works just fine I think.

arrayClean = [];
for(int i = 0; i<array1.length; i++) {
     if(array1[i].length < 3) {
          arrayClean[i] = array[i];
     }
}
pmat
  • 43
  • 6