Q:

Write a JavaScript program to join all elements of an array into a string and returns this string. Uses a separator and an end separator

0

Write a JavaScript program to join all elements of an array into a string and returns this string. Uses a separator and an end separator.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

const join = (arr, separator = ',', end = separator) =>
  arr.reduce(
    (acc, val, i) =>
      i === arr.length - 2
        ? acc + val + end
        : i === arr.length - 1
          ? acc + val
          : acc + val + separator,
    ''
  );
console.log(join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'));
console.log(join(['pen', 'pineapple', 'apple', 'pen'], ','));
console.log(join(['pen', 'pineapple', 'apple', 'pen']));

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now