I should create a function that given an array of numbers and a specific value, returns another array filled with those numbers in which the number of digits matches the specified value.
function filtrarPorQuantidadeDeDigitos (array, nDigitos) {
let solucao = array.filter(elemento => {
elemento.toString().length === nDigitos
console.log(elemento.toString().length == nDigitos)
})
return solucao
}
console.log(filtrarPorQuantidadeDeDigitos([123, 11, 158, 0], 3))
Thus I created an arrow function associated with the .filter method that converts each number in a string (.toString()) and then, counts its length to check if it’s the same as what we are expecting. Naturally, if the condition was fulfilled, that element would be copied to the resulting array. However, even checking with a console.log that the boolean values for each loop are correct, I still get an empty array as output.
Why isn’t it working? What should I do to solve this problem? Is it possible to do it in any similar way?
2
Answers
When the filter function is simple, i.e. can be given as an expression, not requiring multiple steps, you can write it like this:
If it is more complex, you can use several statements grouped with
{ }
, but you must then give areturn
statement at the end.Your code just needs that fixed:
You need to return the value if the result is true. Like this:
In the example above I check if the length is equal to nDigits, if it is the arrow function in the filter returns true and the element is added to the new filtered array, otherwise it returns false and the element is not added.
Since arrow functions accept the implicit return, the one that can just pass an expression and it returns automatically, so you can just do it like this:
If you want to add a console to display the data, then you can do like this: