Sanchit Kumar
Sanchit Kumar

Reputation: 45

How do I remove alternating commas from an array in JavaScript, combining adjacent entries into one?

If I have an array such as:

let arr = ["SO", "WHATS", "UP", "HELLO", "Cool", "Cat"];

How can I transform the array so that every other comma in the array is removed and adjacent items are combined, resulting in:

let result = [ "SO WHATS", "UP HELLO", "Cool Cat" ];

Upvotes: 0

Views: 100

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

You want to reduce every two items into one item:

const result = [ "SO WHATS", "UP HELLO", "Cool Cat" ];

Example

const packItems = (arr, count) => {
  return arr.reduce((result, item, index) => {
    if (index % count === 0) {
      result.push([item]);
    } else {
      result[result.length - 1].push(item);
    }
    return result;
  }, []).map(item => item.join(' '));
};

console.log(packItems(["SO", "WHATS", "UP", "HELLO", "Cool", "Cat"], 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 193358

Given this expected result - const result = [ "SO WHATS", "UP HELLO", "Cool Cat" ];, you can create the new array using Array.from(), and then slice 2 items from the original array, and join them with a space:

const arr = ["SO", "WHATS", "UP", "HELLO", "Cool", "Cat"]

const result = Array.from(
  { length: Math.ceil(arr.length / 2) },
  (_, i) => arr.slice(i * 2, i * 2 + 2).join(' ')
)

console.log(result)

Upvotes: 3

pilchard
pilchard

Reputation: 12957

Here is a compact example that also accounts for trailing elements.

const arr = ["SO", "WHATS", "UP", "HELLO", "Cool", "Cat", "!"];

function compactArr(array, count) {

  return array.reduce((a, e, i) => 
    (i%count ? a[a.length-1] += ` ${e}` : a = [...a, e], a), []);   

}

console.log('2: ', compactArr(arr, 2));
console.log('5: ', compactArr(arr, 5));
console.log('1: ', compactArr(arr, 1));

Upvotes: 2

M.Handzar
M.Handzar

Reputation: 26

Array elements are separated by commas, and cannot be removed. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Upvotes: -1

Related Questions