Skip to content
Advertisement

Array filter method is not returning trimmed values

let un_trimmed = ["push", " pop", "shift", "  "];
filtered = un_trimmed.filter(function (el) {
  return el.trim();
});

// output :
["push", " pop", "shift"] (notice the un-trimmed value of ” pop”)
// Expected output :
["push", "pop", "shift"] (notice the trimmed value of “pop”)

What am I doing wrong ?

Advertisement

Answer

Array.filter only uses the return value to decide whether to include the input value in the output or not; it does not modify the input value. To do that, use map then filter:

let un_trimmed = ["push", " pop", "shift", "  "];
filtered = un_trimmed.map(function (el) {
  return el.trim();
}).filter(Boolean);
console.log(filtered);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement