0

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(' ');
  }
}
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 12 '21 at 01:19

1 Answers1

4

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)

Spectric
  • 30,714
  • 6
  • 20
  • 43
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320