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

167
Views
How can I extract letters of an array of strings into an array, split by space in JavaScript?

Here is a code snippet that explains what I am trying to do..

const names = ["foo", "bar", "baz"];
let actual = [];
// Implementation here..
const expected = ['f', 'o', 'o', ' ', 'b', 'a', 'r', ' ', 'b', 'a', 'z'];

// Tests
if (actual.length !== expected.length) {
  console.error("Fail - Arrays not in equal length.");
}
for (let i = 0; i < expected.length; i++) {
  if (actual[i] !== expected[i]) {
    console.error('Fail - Letters are not equal in indices.');
    break;
  }
}

I do have an implementation for it but is there a simpler/elegant way to do this instead of using nested loops and an if condition to check to see if we are iterating over the last element?

Here what works for me which I do not like and want to improve:

for (const name of names) {
  for (const letter of [...name]) {
    actual.push(letter);
  }
  if (names[names.length - 1] !== name) {
    actual.push(' ');
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Sounds like it'd be easy to just join the array of strings by a space, then turn that into an array:

const names = ["foo", "bar", "baz"];
const result = [...names.join(' ')];

console.log(result);

(you might be tempted to .split('') for more elegant looking chaining, but that has problems with certain characters)

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!