0

If given an array of elements let array = ['apple', 'banana', 'salami', 'cheese']

What is the best practice to get this result : ['applebanaa' , 'salamicheese']

My first thought was to use reduce which works but it concatenates every string into one long string. See example below

```let array = ['apple', 'banana', 'salami', 'cheese']"

array.reduce((a,b) => a + b);

output : applebanaasalamicheese```

I feel like I am on the right track here. Maybe I need to do something to the equation within the parenthesis of reduce to get the result I am looking for?

I am relatively new to Javascript, but I hope that this question is clear enough to follow. Thanks in advance for any help!

Best Regards

Saebel
  • 9

4 Answers4

1

reduce will be very slightly unwieldly here. The output structure is an array of strings that isn't one-to-one with the input, and the desired output isn't a number or primitive. Easier to create a variable outside the loop and push to it than to return the same accumulator array each time.

A plain for loop that iterates over indicies i and i + 1 at a time would work.

const array = ['apple', 'banana', 'salami', 'cheese'];
const output = [];
for (let i = 0; i < array.length; i += 2) {
  output.push(array[i] + (array[i + 1] || ''));
}
console.log(output);

If you really wanted to use .reduce...

const array = ['apple', 'banana', 'salami', 'cheese'];
const output = array.reduce((a, str, i) => {
  if (i % 2 === 0) {
    a.push(str);
  } else {
    a[a.length - 1] += str;
  }
  return a;
}, []);
console.log(output);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Your solution is good. But I suggest you should check if the array length is odd (1,3, 5, ...) before concatenation. `array[i + 1]` may return `'undefined'`, it's cause unexpected results. – Thanh Dao Jun 20 '22 at 03:02
  • Yeah, though OP did not specify what should happen under such circumstances, or if such circumstances could even happen... if the last element should be the single string, or omitted altogether, or throw an error, or something else – CertainPerformance Jun 20 '22 at 03:03
  • How would you set this up to work for arrays that have an odd length. – Saebel Jun 20 '22 at 03:05
  • @Saebel See my above comment - what do you want to happen in such a circumstance? Throw an error, omit the last element, have the last element be only the single string, or what? You should specify that in your question if it's something you want to be addressed as well – CertainPerformance Jun 20 '22 at 03:06
  • How would you write this to also work for an array with an odd length. So that if you had ```['apple', 'banana', 'salami', 'cheese', 'goat']``` it would return ```['applebana', 'salamicheese', 'goat']``` and not ```['applebana', 'salamicheese', 'goatundefined']```; – Saebel Jun 20 '22 at 03:08
  • @Saebel Just alternate with the empty string when inserting the second element - `|| ''` will do it for you – CertainPerformance Jun 20 '22 at 03:10
  • You are Incredible!!! – Saebel Jun 20 '22 at 03:13
1

You can use Array.prototype.reduce() combined with Array.prototype.concat()

Code:

const array = ['apple', 'banana', 'salami', 'cheese']

const result = array.reduce((a, c, i, arr) => 
  a.concat(i % 2 === 0 ? [c + (arr[i + 1] || '')] : []), [])

console.log(result)

Also you can use Array.prototype.filter() combined with Array.prototype.map()

Code:

const array = ['apple', 'banana', 'salami', 'cheese']

const result = array
  .filter((_, index) => index % 2 === 0)
  .map((item, index) => item + (array[index * 2 + 1] || ''))

console.log(result)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

if you only want to join strings you can use array.join()

const sampleArray = ['apple', 'banana', 'salami', 'cheese']
const joinedArray = SampleArray.join(' ') // "apple banana salmi cheese"

you can choose space (' ') or comma for the separator, see here for the docs Array.join()

baihakhi
  • 41
  • 5
0

It appears that the patterns you are looking for is chunk(2) and map(join('')) chunk is available with lodash among other libraries, or you can implement it yourself.

// If given an array of elements let array = ['apple', 'banana', 'salami', 'cheese']
// What is the best practice to get this result : ['applebanaa' , 'salamicheese']

const array = ['apple', 'banana', 'salami', 'cheese'];

// https://lodash.com/docs/4.17.15#chunk
// https://stackoverflow.com/questions/8495687/split-array-into-chunks
function chunk(array, size = 1) {
  let chunked = [];
  for (let i = 0; i < array.length; i+=size) {
    chunked.push(array.slice(i, i+size));
  }
  return chunked;
}

/* Chunk will divide up the array in to size batches
 * and return an array of arrays of elements of the
 * chunk size.
 */

// const chunked = chunk(array, 2);
// chunked = [['apple', 'banana'], ['salami', 'cheese']];

// Here is the final expression
console.log(
  chunk(array, 2)
    .map(chunk => chunk.join(''))
);
Doug Coburn
  • 2,485
  • 27
  • 24