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
>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], '-'));