var array = ["Red", "Green", "White", "Black", "Gray"];
document.write(array.join("+"));
I want it to output like this: Red+Green-White*Black#Gray
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)
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);
(i => (a, b) => [a, b].join(separators[++i, i%= separators.length]))(-1) can just be (a, b, i) => [a, b].join(separators[i]) ;)[i-1] instead of [i]. I do appreciate the Scheme style here, though.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!
reducemethod.