Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take an array, and insert commas between each item?

I am trying to understand how to take an array like [1,2,3,4,5] and then between each index, add a , so the array becomes [1, ', ', 2, ', ', 3, ', ', 4, ', ', 5]

I know it sounds stupid but I'm having some issues with it.

Basically, I want to use something like splice() method, so that I can iterate over the array and each odd index, I can do splice(index, 0, ', ').

like image 908
user1354934 Avatar asked Feb 20 '17 18:02

user1354934


3 Answers

You can use .reduce method which accepts as parameter a callback function.

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

var array=[1,2,3,4,5];
console.log(array.reduce(function(a,b){
    return a.concat(b).concat(",");
},[]).slice(0,-1));
like image 123
Mihai Alexandru-Ionut Avatar answered Oct 19 '22 22:10

Mihai Alexandru-Ionut


Use .reduce()

  1. Start with empty array
  2. Push an element of array then push ', '
  3. At last remove last ', ' using .pop()

var array1 = [1, 2, 3, 4, 5]

var array2 = array1.reduce(function(acc, val) {
  acc.push(val);
  acc.push(', ');
  return acc;
}, []);

array2.pop();

console.log(array2);
like image 24
Sangharsh Avatar answered Oct 20 '22 00:10

Sangharsh


You can use reduce to create a new array with the inserted values:

function weaveArray(array, weaveValue) {
  const {length} = array;
  return array.reduce((result, value, i) => {
    if(i < length - 1) {
      result.push(value, weaveValue);
    } else {
      result.push(value);
    }
    return result;
  }, []);
}

console.log(
  weaveArray([1,2,3,4,5], ",")
);
like image 33
SimpleJ Avatar answered Oct 20 '22 00:10

SimpleJ