In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will get output as ab,cd,ef,g
Javascript and Python program to concatenate the string element in an array with its preceding string element.
Javascript:
1 2 3 4 5 6 7 8 | const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; let result = []; for(let i=0; i <= arr.length-1; i = i+2){ let temp = arr[i] + (arr[i+1] ? arr[i+1] : ""); result.push(temp) } print(result); |
Output:
ab, cd, ef, g
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | arr = ['a', 'b', 'c', 'd', 'e']; result = []; i=0 length = len(arr) while i <= length-1: t="" try: t=arr[i+1] except IndexError: t="" temp = arr[i] + t result.append(temp) i += 2 print(result) |
Output:
['ab', 'cd', 'ef', 'g']