How can I filter objects in an Array with Typescript?

Asked

Viewed 2,071 times

0

Example:

function isBigEnough(element, index, array) { 
   return (element >= 10); 
} 

var passed = [12, 5, 8, 130, 44].filter(isBigEnough); 
console.log("Test Value : " + passed );
  • Exactly the same way you did.

  • 1

    I took this example in a booklet. I was able to understand by Noobsaibot’s reply.

1 answer

0


The function filter came to facilitate life, if it was not created, you would have to traverse the object using for / for...in and or forEach, making the condition and adding the element that passed the test on a new object, see the examples:

let objetos = [12, 5, 8, 130, 44];
let resultadoA = [],
    resultadoB = [],
    resultadoC = [];

for (let i = 0; i < objetos.length; i++) {
  if (objetos[i] >= 10) {
    resultadoA.push(objetos[i]);
  }
}

for (let objB of objetos) {
  if (objB >= 10) {
    resultadoB.push(objB);
  }
}

objetos.forEach(objC => {
  if (objC >= 10) {
    resultadoC.push(objC);
  }
});

console.log(JSON.stringify(resultadoA), JSON.stringify(resultadoB), JSON.stringify(resultadoC));

Already using the function filter, it will go through the array and call the function that was informed, passing as parameter: the current element, the current index and the array. If you print these parameters on the console, you will get the following result:

12  // Primeiro elemento do array
0   // Índice 0
[12, 5, 8, 130, 44]
5   // Segundo elemento do array
1   // Índice 1
[12, 5, 8, 130, 44]
8   // Terceiro elemento do array
2   // Índice 2
[12, 5, 8, 130, 44]
130 // Quarto elemento do array
3   // Índice 3
[12, 5, 8, 130, 44]
44  // Quinto elemento do array
4   // Índice 4
[12, 5, 8, 130, 44]

Note that it traversed the array element by element, and returned a new array with the elements that passed the test:

"Test Value : 12,130,44"

In addition to the example given in the question, you can also do so:

var resultadoA = ['PHP', 'C#', 'Java', 'JavaScript'].filter(el => el === 'JavaScript');

// Retornada array vazio, porque nenhum elemento
// passou no teste.
var resultadoB = ['PHP', 'C#', 'Java', 'JavaScript'].filter(el => el === 'Python');

console.log(JSON.stringify(resultadoA),JSON.stringify(resultadoB));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.