1

var array = ["Red", "Green", "White", "Black", "Gray"];
document.write(array.join("+"));

I want it to output like this: Red+Green-White*Black#Gray

1
  • you can do this with a reduce method. Commented Jun 18, 2020 at 18:18

3 Answers 3

2

You could do something like this:

// your initial array of elements to join
var array = ["Red", "Green", "White", "Black", "Gray"];

// new list of separators to use
var separators = ["+","-","*","#"];

var joined = array.reduce((output, elem, index) => {
  // always join the next element
  output += elem;

  // add next separator, if we're not at the final element in the array
  if (index < array.length - 1) output += separators[index];

  // return the current edits
  return output;
}, '')

console.log(joined)

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

Comments

1

You could reduce by taking an array for glue.

var array = ["Red", "Green", "White", "Black", "Gray"],
    glue = ['+', '-', '*', '#'],
    result = array.reduce((a, b, i) => [a, b].join(glue[(i - 1) % glue.length]));

console.log(result);

3 Comments

(i => (a, b) => [a, b].join(separators[++i, i%= separators.length]))(-1) can just be (a, b, i) => [a, b].join(separators[i]) ;)
@VLAZ, the index starts with one.
You are right! Sorry, I missed that. But then it's [i-1] instead of [i]. I do appreciate the Scheme style here, though.
0

Assuming that the delimiters are random and don't contain any logic. You can have a look at the following code:

var chars = ['a', 'b', 'c', 'd'];
var delimiters = ['+', '-', '*', '#'];

function customJoin(resultantStr, num) {
    let delimiter = delimiters[Math.floor(Math.random()*delimiters.length)];
  return resultantStr+delimiter+num;
}

console.log(chars.reduce(customJoin))

Let me know if this is helpful to you! Happy Coding!

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.