1

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.

1
  • 1
    "I'm currently learning Javascript.." is not a reason to only learn by provided code. Where is your attempt to solve this yourself? Commented Mar 20, 2022 at 16:41

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.