How to filter an array using the For structure?

1

How can I filter an array using the for structure?

The code is this:

const numeros = [1,2,3,4,5,55,190,355,747,1000,125];
  

I need to filter the numbers under 10.

I used it this way, but I was asked to create one using the for structure and I can not get out of 0.

const numeros = [1,2,3,4,5,55,190,355,747,1000,125];

const filterOne = x => x < 10;

const filterTwo = numeros.filter(filterOne);

console.log(filterTwo);
    
asked by anonymous 23.01.2018 / 01:59

2 answers

3

Just do one condition, it can also be done like this:

numeros.forEach((n) => {
  if (n < 10) {
    filterTwo.push(n);
  }
});

const numeros = [1,2,3,4,5,55,190,355,747,1000,125];

const filterOne = x => x < 10;
const filterTwo = [];

for (let i = 0; i < numeros.length; i++) {
  // Verifica que o valor de "numeros" no índice "i" é menor que 10
  if (numeros[i] < 10) {
    // adiciona no array filterTwo 
    filterTwo.push(numeros[i]);
  }
}

console.log(filterTwo);

Reference:

23.01.2018 / 02:05
2

You can use another loop form, forEach , where the (e) parameter represents the value of each item in the array:

const numeros = [1,2,3,4,5,55,190,355,747,1000,125];

const result = [];
numeros.forEach((e)=>{
   e < 10 && result.push(e);
});

console.log(result);

Explanation of the # used in the above example:

Returns the second operand based on the value of the first operand. If the first one is false , the second operand is ignored.

e < 10 && result.push(e);
\____/  ↑ \____________/
 1º op. |     2º op.
        |
O 1º op. tem que ser true

e < 10 || result.push(e);
\____/  ↑ \____________/
 1º op. |     2º op.
        |
O 1º op. tem que ser false

does not meet the 1st op., similar to ? ):

e < 10 ? faz uma coisa : faz outra coisa;
    
23.01.2018 / 02:14