Philippe
Philippe

Reputation: 1040

How to insert a new element at any position of a JS array?

I have an array [a, b, c]. I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0].

I guess it would be something like this, but I can't make it works.

for (let i = 0; i < array.length; i++) {
    newArray = [
        ...array.splice(0, i),
        0,
        ...array.splice(i, array.length),
    ];
}

Thank you for helping me!

Upvotes: 35

Views: 30130

Answers (20)

Simon
Simon

Reputation: 1513

A fast solution not in-place: (based on my >10x flatMap (similar use-case))

function arrayJoin(inp, sep) {
  let tar = new Array(inp.length * 2 + 1)
  for (let i = inp.length - 1; i > -1; --i) {
    tar[i * 2 + 1] = inp[i]
    tar[i * 2] = sep
  }
  tar[inp.length * 2] = sep
  return tar
}

// Verify
let inp = arrayJoin(["a", "b", "c"], 0)
console.log(inp.join(" "))

If you need modification (in-place) use the while {splice} approach

Upvotes: 0

Nav
Nav

Reputation: 71

Thanks for your question and thanks to all contributors, for their answers. This would be my approach

const arr = ["a", "b", "c"];
let toAdd = 0;
for (let i = 0; i <= arr.length; i += 2) {
  arr.splice(i, 0, toAdd);
}
console.log(arr);

or

const arr = ["a", "b", "c"];
let toAdd = 0;
const newArr = [];
newArr.unshift(toAdd);
for (let i = 0; i < arr.length; i++) {
  newArr.push(arr[i]);
  newArr.push(toAdd);
}
console.log(newArr);

Cheers Nav

Upvotes: 0

Ben Golding
Ben Golding

Reputation: 776

I think this is correct, ie, just adds the element between the elements of the array, and should be pretty efficient:

const intersperse = ([first, ...tail]: any[], element: any) => (
    (first === undefined) ? [] : [first].concat(...tail.map((e) => [element, e]))
);

console.log(intersperse([], 0));
console.log(intersperse([1], 0));
console.log(intersperse([1, 2, 3], 0));

Upvotes: 0

Gabriel Petersson
Gabriel Petersson

Reputation: 10522

Straight forward way of inserting only between:

const arr = ['a', 'b', 'c'];

arr.map((v, i) => !i || i === arr.length - 1 ? [v] : [0, v]).flat() 

Upvotes: 0

Alok
Alok

Reputation: 297

You can try with the below code. It will add 0 in middle of each two element of the array

console.log(['a', 'b', 'c'].reduce((r, a) => r.concat(a,0), [0]).slice(1, -1))

Upvotes: 2

snazzybouche
snazzybouche

Reputation: 2424

If you want to insert elements only after existing ones:

console.log(["a", "b", "c"].map(i => [i, 0]).flat())

Upvotes: 1

Mengo
Mengo

Reputation: 1267

Another way is to use some functional methods like zip and flat. Check out lodash.

const array = ['a', 'b', 'c']
const zeros = Array(array.length + 1).fill(0)
const result = _.zip(zeros, array).flat().filter(x => x !== undefined)
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 0

x-magix
x-magix

Reputation: 2858

all of the above methods in very long strings made my android computer run on React Native go out of memory. I got it to work with this

let arr = ['a', 'b', 'c'];
let tmpArr = [];

for (const item in arr) {
  tmpArr.push(item);
  tmpArr.push(0);
}

console.log(tmpArr);

Upvotes: 0

Sebastian Barth
Sebastian Barth

Reputation: 4551

Another ES6+ version using flatmap (if creation of a new array instead is ok):

['a', 'b', 'c', 'd']
    .flatMap((e, index) => index ? [e, 0] : [0, e, 0])

Upvotes: 7

Yangshun Tay
Yangshun Tay

Reputation: 53229

let arr = ['a', 'b', 'c'];

function insert(items, separator) {
  const result = items.reduce(
    (res, el) => [...res, el, separator], [separator]);
  return result;
}

console.log(insert(arr, '0'));

Upvotes: 0

Vincent Menant
Vincent Menant

Reputation: 475

Another way if you want to exclude the start and end of array is :

var arr = ['a', 'b', 'c']
var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b))

console.log(newArr)

Upvotes: 17

Nina Scholz
Nina Scholz

Reputation: 386883

For getting a new array, you could concat the part an add a zero element for each element.

var array = ['a', 'b', 'c'],
    result = array.reduce((r, a) => r.concat(a, 0), [0]);
    
console.log(result);

Using the same array

var array = ['a', 'b', 'c'],
    i = 0;

while (i <= array.length) {
    array.splice(i, 0, 0);
    i += 2;
}

console.log(array);

A bit shorter with iterating from the end.

var array = ['a', 'b', 'c'],
    i = array.length;

do {
    array.splice(i, 0, 0);
} while (i--)

console.log(array);

Upvotes: 27

Redu
Redu

Reputation: 26201

This looks like the intersperse algorithm but does some addition to the head and tail as well. So i call it extrasperse.

var arr         = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    extrasperse = (x,a) => a.reduce((p,c,i) => (p[2*i+1] = c, p), Array(2*a.length+1).fill(x));

console.log(JSON.stringify(extrasperse("X",arr)));

Upvotes: 0

Cody Fortenberry
Cody Fortenberry

Reputation: 200

It could be done with strings by splitting and joining.

var arr = ['a', 'b', 'c'];
var newArray = ("0," + arr.toString().split(",").join(",0,")).split(",");
console.log(newArray);

Upvotes: 0

Pako Navarro
Pako Navarro

Reputation: 168

Another way:

var a = ['a', 'b', 'c'],
  b;

b = a.reduce((arr, b) => [...arr, b, 0], []);

console.log(b);

Upvotes: 4

JLRishe
JLRishe

Reputation: 101778

You could use .reduce():

function intersperse(arr, val) {
  return arr.reduce((acc, next) => {
    acc.push(next);
    acc.push(val);
    return acc;
  }, [val]);
}

console.log(intersperse(['a', 'b', 'c'], 0));

Or to accomplish this by modifying the original array:

function intersperse(arr, val) {
  for (let i = 0; i <= arr.length; i += 2) {
    arr.splice(i, 0, val);
  }

  return arr;
}

console.log(intersperse(['a', 'b', 'c'], 0));

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122155

You can use map() with ES6 spread syntax and concat()

var arr = ['a', 'b', 'c']
var newArr = [0].concat(...arr.map(e => [e, 0]))

console.log(newArr)

Upvotes: 9

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

function insert(arr, elm) {
  var newArr = [];
  for(var i = 0; i < arr.length; i++) {   // for each element in the array arr
    newArr.push(elm);                     // add the new element to newArr
    newArr.push(arr[i]);                  // add the current element from arr
  }
  newArr.push(elm);                       // finally add the new element to the end of newArr
  return newArr;
}

console.log(insert(["a", "b", "c"], 0));

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32175

You just need to loop over the array elements and add the new element in each iteration, and if you reach the last iteration add the new element after the last item.

This is how should be your code:

var arr = ['a', 'b', 'c'];
var results = [];
arr.forEach(function(el, index) {
  results.push(addition);
  results.push(el);
  if (index === arr.length - 1)
        results.push(addition);
});

Demo:

This is a Demo snippet:

var arr = ['a', 'b', 'c'];
var results = [];
var addition = 0;
arr.forEach(function(el, index) {
  results.push(addition);
  results.push(el);
  if(index === arr.length -1)
        results.push(addition);
});
console.log(results);

Upvotes: 1

marvel308
marvel308

Reputation: 10458

You could do

let arr = ['a', 'b', 'c'];

arr = arr.reduce((a, b) => {
    a.push(0);
    a.push(b);
    return a;
}, []);
arr.push(0);
console.log(arr);

Upvotes: 0

Related Questions