6

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, ', ').

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
user1354934
  • 8,139
  • 15
  • 50
  • 80
  • 1
    Instead of trying to modify your array, return a new one - this will be easier to achieve. – georg Feb 20 '17 at 18:42
  • A quick hack: `arr.join(',').split('');` - the JS engine will prefer them all being the same type (you'll have an array of strings) but it depends if you actually need mixed strings with number types or not. – Luke Briggs Feb 20 '17 at 18:44
  • For ES6, duplicate of http://stackoverflow.com/questions/37128624/terse-way-to-intersperse-element-between-all-elements-in-javascript-array. – kennytm Feb 20 '17 at 18:44
  • Thanks. I am trying to follow JS interview questions, and one of them is to add some text to console.log. I am able to answer that question correctly, so I am trying to challenge myself to add comma seperation (I know console log does NOT do this), but now I am failing my own challenge – user1354934 Feb 20 '17 at 18:45
  • _"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, ', ')"_ Start index at `1`, increment index passed to `.splice()` by `2`. – guest271314 Feb 20 '17 at 19:11

7 Answers7

5

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));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
3

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);
Sangharsh
  • 2,999
  • 2
  • 15
  • 27
2

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], ",")
);
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
1

With just two methods:

Edit

If you want to save your commas use some regexp instead:

var c = a.join(', , , ').split(/\s(?=,\s)/);

var a = [1,2,3,4,5];
var b = a.join(' , ').split(' ');
var c = a.join(', ,  , ').split(/\s(?=,\s)/);
console.log(b,c);
Paweł
  • 4,238
  • 4
  • 21
  • 40
  • see my comment above - you may wish to mention that the types do not match the question. – Luke Briggs Feb 20 '17 at 18:47
  • your comment is bad because with `22`, `33` values it will divide it into `2`, `2` etc. – Paweł Feb 20 '17 at 18:49
  • I was only considering single numbers in the comment, but it doesn't change the information about types (specifically, JS engines _hate_ mixed type arrays - an array of all strings is much better). – Luke Briggs Feb 20 '17 at 18:51
1

console.log([1,2,3,4,5].reduce(function(acc, val, idx, list) {
  acc.push(val);
  if (idx < list.length - 1) {
    acc.push(',');

  }
  return acc;
}, []));
rasmeister
  • 1,986
  • 1
  • 13
  • 19
1

Short solution using Array.prototype.join(), Array.prototype.map() and String.prototype.match() functions:

var arr = [1,2,3,4,5],
    newArr = arr.join(',').match(/\w+|\W+/g).map(function(v){
        return (isNaN(v))? v : +v;  // considering numeric values
    });

console.log(newArr);

You wanted splice approach? Here it is:

var arr = [1,2,3,4,5];
for (var i = 1; i < arr.length; i+=2) {
    arr.splice(i, 0, ',');
}

console.log(arr);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

You can use a variable at .splice() to increment index by 2

var arr = [1,2,3,4,5];
for (let i = 1, len = arr.length * 2; arr.length < len - 1; arr.splice(i, 0, ","), i += 2);
console.log(arr);
guest271314
  • 1
  • 15
  • 104
  • 177