Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace elements in array with elements of another array

I want to replace elements in some array from 0 element, with elements of another array with variable length. Like:

var arr = new Array(10), anotherArr = [1, 2, 3], result; result = anotherArr.concat(arr); result.splice(10, anotherArr.length); 

Is there some better way?

like image 838
Artem Svirskyi Avatar asked Jul 07 '13 10:07

Artem Svirskyi


People also ask

How can you remove an element from an array and replace it with a new one?

splice() method can be used to add, remove, and replace elements from an array. This method modifies the contents of the original array by removing or replacing existing elements and/or adding new elements in place. Array. splice() returns the removed elements (if any) as an array.

What method is used to create a new array using elements of another array?

The method arr. concat creates a new array that includes values from other arrays and additional items. It accepts any number of arguments – either arrays or values.


1 Answers

You can use the splice method to replace part of an array with items from another array, but you have to call it in a special way as it expects the items as parameters, not the array.

The splice method expects parameters like (0, anotherArr.Length, 1, 2, 3), so you need to create an array with the parameters and use the apply method to call the splice method with the parameters:

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr)); 

Example:

var arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']; var anotherArr = [ 1, 2, 3 ];  Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));  console.log(arr); 

Output:

[ 1, 2, 3, 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

Demo: http://jsfiddle.net/Guffa/bB7Ey/

like image 146
Guffa Avatar answered Sep 28 '22 03:09

Guffa