I'm getting an array and strigifying it in this array variable:
let arrayStr = oldArr.join(', ');
My array looks like this in console:
(a), text1, (b), text2, (c), text3, (d), text3
What I want is to make it look like this:
(a) - text1, (b) - text2, (c) - text3, (d) - text3
I know that I've added ', ' after all strings, but how can I apply it like above?
Thanks.
You can achieve this by looping through the array and accessing the current item and also the following one by its index and then appending both to the same element of a new array, something like this:
var oldArr = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text3'];
var newArr = [];
for (var i = 0; i < oldArr.length; i++) {
newArr.push(oldArr[i] + ' - ' + oldArr[++i]);
}
console.log(newArr.join(', '));
You could use a three step solution, first get all items who are connected in a single sub array, map the joinded sub arrays and joun the outer array.
var array = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text3'],
text = array
.reduce(function (r, a, i) {
i % 2 ? r[r.length - 1].push(a) : r.push([a]) ;
return r;
}, [])
.map(function (a) {
return a.join(' - ');
})
.join(', ');
console.log(text);
You can loop through all the array elements and make use of %(modulo) operator to combine the values as you need:
var oldArr = ['(a)', 'text1', '(b)', 'text2', '(c)', 'text3', '(d)', 'text4'];
var arrayStr = [];
for (var i = 0; i < oldArr.length; i++) {
if (i % 2 != 0) {
oldArr[i] = oldArr[i - 1] + ' - ' + oldArr[i] ;
arrayStr.push(oldArr[i]);
}
}
console.log(arrayStr.join(', '));