1

I want to make a function that completely override the original array.

function putDatainthis(arr) {
 //....some ways to get data
 arr = [data,data,data...]; //this just reassigns arr = to new array original that was passed as reference hasn't been modified.
}

//so right now only way i can think of is this:

function putDatainthis(arr) {
 var data = [3,4,6,2,6,1];
 arr.length=0;
 data.forEach(function(e){
 arr.push(e);
 });
}

but i want to know can it be improved or is there more native way.

cнŝdk
32.2k7 gold badges62 silver badges81 bronze badges
asked Sep 7, 2015 at 16:11
1
  • basically i want replace function Commented Sep 7, 2015 at 16:15

3 Answers 3

3

The Array.prototype.splice() function is what you are looking for, this is your way to go:

function putDataInThis(arr) {
 var data = [3, 4, 6, 2, 6, 1];
 arr.length = 0;
 arr.splice(0, arr.length, data);
 return arr;
}
alert(putDataInThis(["h", "g"]).join(","));

Explantation:

In the following arr.splice(0, arr.length, data) statement, we used splice() function with the following parameters:

  • 0 the beginning index for the replacement.
  • arr.length as the number of elements to replace.
  • And data is the list of new values to put in our array.

Read Array.splice( ): insert, remove, or replace array elements for further information.

answered Sep 7, 2015 at 16:40
Sign up to request clarification or add additional context in comments.

Comments

1

I think you could use jquery merge.

function putDatainthis(arr) {
 var data = [3,4,6,2,6,1];
 $.merge(arr, data);
}
answered Sep 7, 2015 at 16:31

1 Comment

i will be using it in nodejs
0

Try this way.

function putDatainthis(arr) {
 var data = [3,4,6,2,6,1]; 
 var concat_array = data.concat(arr);
}
answered Sep 7, 2015 at 16:37

1 Comment

arr has not changed in this example

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.