How to 'Join' an Array Adding to the Beginning of the Resulting String the First Character to Join

How can I 'join' an array adding to the beginning of the resulting string the first character to join?

The whole point of join is that you only get characters between the joined items. You want one in front of every item. I don't know of a short way, but it seems more natural just to map them and then join them without a delimiter:

["name1", "name2"].map{|item| '&'+item}.join

How does one join string-type array-items, each with a comma character, except for the last item which has to be joined by and?

without temporarily saved references but with mutation of the original strings array ...

const strings = ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'];

console.log(
[strings.pop(), strings.join(', ')].reverse().join(' and ')
);
console.log('mutated ... strings :', strings);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Ruby: how to add separator character to the last?

No, there is no single function like that. You can just hack it like this:

arr.push('').join('-')

If you don't want to change the original array. dup it:

arr.dup.push('').join('-')

How can I join elements of an array in Bash?

A 100% pure Bash function that supports multi-character delimiters is:

function join_by {
local d=${1-} f=${2-}
if shift 2; then
printf %s "$f" "${@/#/$d}"
fi
}

For example,

join_by , a b c #a,b,c
join_by ' , ' a b c #a , b , c
join_by ')|(' a b c #a)|(b)|(c
join_by ' %s ' a b c #a %s b %s c
join_by $'\n' a b c #a<newline>b<newline>c
join_by - a b c #a-b-c
join_by '\' a b c #a\b\c
join_by '-n' '-e' '-E' '-n' #-e-n-E-n-n
join_by , #
join_by , a #a

The code above is based on the ideas by @gniourf_gniourf, @AdamKatz, @MattCowell, and @x-yuri. It works with options errexit (set -e) and nounset (set -u).

Alternatively, a simpler function that supports only a single character delimiter, would be:

function join_by { local IFS="$1"; shift; echo "$*"; }

For example,

join_by , a "b c" d #a,b c,d
join_by / var local tmp #var/local/tmp
join_by , "${FOO[@]}" #a,b,c

This solution is based on Pascal Pilz's original suggestion.

A detailed explanation of the solutions previously proposed here can be found in "How to join() array elements in a bash script", an article by meleu at dev.to.

Beginning at the end of 'a', insert 'b' after every 3rd character of 'a'

You could replace the string with a regular expression.

function insertEveryThree(a, b) {
return a.replace(/(?=(...)+$)/g, b);
}

console.log(insertEveryThree('actionable', '-')) // a-cti-ona-ble
console.log(insertEveryThree('1234567', '.')) // 1.234.567
console.log(insertEveryThree('abcde', '$')) // ab$cde
console.log(insertEveryThree('zxyzxyzxyzxyzxyz', 'w')) // zwxyzwxyzwxyzwxyzwxyz

Is there a way to join the elements in an js array, but let the last separator be different?

Updated answer for 2021!

If the goal is to have a different separator between the penultimate and last elements such as "and" or "or", you can use Intl.ListFormat

It does exactly that, and you get i18n for free.

It's supported in all major browsers except IE11.

Examples:

const vehicles = ['Motorcycle', 'Bus', 'Car'];

const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(formatter.format(vehicles));
// expected output: "Motorcycle, Bus, and Car"

const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });
console.log(formatter2.format(vehicles));
// expected output: "Motorcycle, Bus oder Car"

How to join strings conditionally without using let in javascript

If you put the hours, minutes, and seconds back into an array, you can make another array for the suffixes, add the suffixes by mapping the values, then filter out the resulting substrings that are 1 character or less (which would indicate that there wasn't a corresponding value).

const suffixes = ['h', 'm', 's'];
const [hours, minutes, seconds] = ["", "10", ""]; // combine this with the next line if you can
const hms = [hours, minutes, seconds];
const time = hms
.map((value, i) => value + suffixes[i])
.filter(substr => substr.length > 1)
.join(' ');
console.log(time)


Related Topics



Leave a reply



Submit