Search code examples
javascriptarraystrim

Trim an array of an arrays (Javascript)


I know how to trim all strings in an array (thanks to this article!) through the map() method

let a = [' a ', ' b ', ' c '];

let b = a.map(element => {
  return element.trim();
});

console.log(b); // ['a', 'b', 'c']

But I was wondering how can I trim an array of arrays?

For example let x = [[" a ", " b "], [" c ", " d "]]

Thank you!

P.S: I'm currently learning Javascript.


Solution

  • You can map over the nested arrays as well.

    let data = [[" a ", " b "], [" c ", " d "]]
    
    const result = data.map((d) => d.map((y) => y.trim()));
    
    console.log(result);

    If you want to flatten out the result, you could use flatMap()

    let data = [[" a ", " b "], [" c ", " d "]]
    
    const result = data.flatMap((d) => d.map((y) => y.trim()));
    
    console.log(result);