Q:

insert into array js

// for me lol... pls don't delete!
// use splice to insert element
// arr.splice(index, numItemsToDelete, item); 
var list = ["hello", "world"]; 
list.splice( 1, 0, "bye"); 
//result
["hello", "bye", "world"]
5
myArray.splice(index, 0, item);
2

let chocholates = ['Mars', 'BarOne', 'Tex'];
let chips = ['Doritos', 'Lays', 'Simba'];
let sweets = ['JellyTots'];

let snacks = [];
snacks.concat(chocholates);
// snacks will now be ['Mars', 'BarOne', 'Tex']
// Similarly if we left the snacks array empty and used the following
snacks.concat(chocolates, chips, sweets);
//This would return the snacks array with all other arrays combined together
// ['Mars', 'BarOne', 'Tex', 'Doritos', 'Lays', 'Simba', 'JellyTots']
6
myArray.splice(index, itemsToDelete, item1ToAdd, item2ToAdd, ...)
1

var list = ["foo", "bar"];


list.push("baz");


["foo", "bar", "baz"] // result

3
Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};
1
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
0

New to Communities?

Join the community