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(' ');
  }
}
1

1 Answer 1

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)

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

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.