Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!