Home > other >  Trim an array of an arrays (Javascript)
Trim an array of an arrays (Javascript)

Time:03-21

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.

CodePudding user response:

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);

CodePudding user response:

In addition to the solutions already provided, if you have n levels of nested array and you want to trim the string without flattening the array, you can do it recursively as follows.

let arr = [
  [" a ", " b "],
  [" c ", " d ", ["  e", "f "]]
]

function trimRecursively(arr) {
  return arr.map(x => {
    if (Array.isArray(x)) {
      return trimRecursively(x);
    } else {
      return x.trim();
    }
  })
}

console.log(trimRecursively(arr));

  • Related