Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!
Active reading.
Source Link
Peter Mortensen

Another possible solution, with usage of Array#reduceArray.reduce.

const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];

const insert = (arr, item, index) =>
  arr.reduce(function(s, a, i) {
    i === index ? s.push(item, a) : s.push(a);
    return s;
  }, []); 

console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))

Another possible solution, with usage of Array#reduce.

const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];

const insert = (arr, item, index) =>
  arr.reduce(function(s, a, i) {
    i === index ? s.push(item, a) : s.push(a);
    return s;
  }, []); 

console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))

Another possible solution, with usage of Array.reduce.

const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];

const insert = (arr, item, index) =>
  arr.reduce(function(s, a, i) {
    i === index ? s.push(item, a) : s.push(a);
    return s;
  }, []);

console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))

deleted 19 characters in body
Source Link
kind user

Another possible solution, with usage of Array#reduce.

varconst arr = ["apple", "orange", "raspberry"],"raspberry"];
   const arr2 = [1, 2, 4];

functionconst insert = (arr, item, index) {=>
    arr = arr.reduce(function(s, a, i) {
      i ===== index ? s.push(item, a) : s.push(a);
      return s;
    }, []);   
     
console.log(arr);
}

insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2);)

Another possible solution, with usage of Array#reduce.

var arr = ["apple", "orange", "raspberry"],
    arr2 = [1, 2, 4];

function insert(arr, item, index) {
    arr = arr.reduce(function(s, a, i) {
      i == index ? s.push(item, a) : s.push(a);
      return s;
    }, []);   
    console.log(arr);
}

insert(arr, "banana", 1);
insert(arr2, 3, 2);

Another possible solution, with usage of Array#reduce.

const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];

const insert = (arr, item, index) =>
  arr.reduce(function(s, a, i) {
    i === index ? s.push(item, a) : s.push(a);
    return s;
  }, []); 
 
console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))

Source Link
kind user

Another possible solution, with usage of Array#reduce.

var arr = ["apple", "orange", "raspberry"],
    arr2 = [1, 2, 4];

function insert(arr, item, index) {
    arr = arr.reduce(function(s, a, i) {
      i == index ? s.push(item, a) : s.push(a);
      return s;
    }, []);   
    console.log(arr);
}

insert(arr, "banana", 1);
insert(arr2, 3, 2);

lang-js