Home > other >  How can you concatenate or group multiple strings within the same array?
How can you concatenate or group multiple strings within the same array?

Time:06-20

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

CodePudding user response:

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);

CodePudding user response:

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)

CodePudding user response:

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()

CodePudding user response:

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(''))
);

  • Related