Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to splice an array into an array in javascript

Is there a better way than this to splice an array into another array in javascript

var string = 'theArray.splice('+start+', '+number+',"'+newItemsArray.join('","')+'");'; eval(string); 
like image 424
wheresrhys Avatar asked Aug 28 '09 16:08

wheresrhys


People also ask

How do you splice an array within an array?

Use the array methods slice and splice to copy each element of the first array into the second array, in order. Begin inserting elements at index n of the second array. Return the resulting array. The input arrays should remain the same after the function runs.

What is the alternative of splice in JavaScript?

Alternative of Array splice() method in JavaScript If the count is not passed then treat it as 1. Run a while loop till the count is greater than 0 and start removing the desired elements and push it in a new array. Return this new array after the loop ends.

Can you splice an array?

splice & delete Array item by index The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn't change the original array. The splice( ) method changes an array, by adding or removing elements from it. Note: the Slice( ) method can also be used for strings.

Can you append an array to an array in JavaScript?

To append one array to another, call the concat() method on the first array, passing it the second array as a parameter, e.g. const arr3 = arr1. concat(arr2) . The concat method will merge the two arrays and will return a new array.


1 Answers

You can use apply to avoid eval:

var args = [start, number].concat(newItemsArray); Array.prototype.splice.apply(theArray, args); 

The apply function is used to call another function, with a given context and arguments, provided as an array, for example:

If we call:

var nums = [1,2,3,4]; Math.min.apply(Math, nums); 

The apply function will execute:

Math.min(1,2,3,4); 
like image 146
Christian C. Salvadó Avatar answered Oct 10 '22 19:10

Christian C. Salvadó