Home > Software engineering >  How can I simulate join() method with reduce() method in Javascript?
How can I simulate join() method with reduce() method in Javascript?

Time:02-24

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

CodePudding user response:

Here is an example where I've added some logging to the exampleJoin function so you can see what it is doing. Then there is a final join method at the bottom which is what you are looking for in the end.

const exampleJoin = (arr, separator) => {
  return arr.reduce((acc, el ) => {
    console.log(`string so far: '${acc}', Current element: '${el}'`)
  return acc   el   separator
  }, '');
};

const ret = exampleJoin([1, 2, 3], '-')
console.log(`ret value: ${ret}`)
console.log(`ret value after slice ${ret.slice(0,-1)}`)

const join = (arr, separator) => {
  return arr.reduce((acc, el ) => acc   el   separator, '').slice(0,-1);
};

console.log(join([1, 2, 3], '-'));

The acc is the accumulated value so far, el is the current element being processed and the empty sting is the initial value off the accumulator acc. The slice is to remove the trailing seperator which this method will introduce.

CodePudding user response:

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

CodePudding user response:

Just needed a little tweak:

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

CodePudding user response:

Here you go

const join = (arr, separator) => {
  return arr.reduce((r, v) => r = v   separator, "").slice(0,-1);
};
console.log(join([1, 2, 3], '-'));

CodePudding user response:

This should work fine.

const join = (arr, separator) => {
  return arr.reduce((prev, curr, i) => prev   (i != 0 ? '-' : '')   curr, '')
}

console.log(join([1, 2, 3], '-'));

Don't forget to check for the index for zero, you don't want the separator to be presented before the first element.

  • Related