Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I simulate join() method with reduce() method in Javascript?

I would like to make a function that does the same that join() method, but I don’t know what I’m doing wrong.

const join = (arr, separator) => {
  return arr.reduce((separator, el) => el + separator, separator);
};
console.log(join([1, 2, 3], '-'));

it returns 321- instead of 1-2-3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Reduce works left to right, but the ordering and naming of your parameters may be leading to confusion.

The reduce callback takes two arguments, where the first argument is ‘accumulated value’, and the second is the current element of the array. The ‘accumulated value’ here will be your joined string, so you need to build it up in the right order, starting the string with the first array element and not the separator itself.

So, to accomplish this, avoid using a default value for the reduce call, and instead return the joined string (so far) plus the separator plus the current element. Make sure to handle the case of an empty array in some way as well.

const join = (arr, separator) => {
  if (!arr.length) return "";
  return arr.reduce((joined, el) => joined + separator + el);
};
console.log(join([1, 2, 3], '-'));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading