3

I want to create a new Array method without modifying the original array.

my_array.push('foo') //modifies my_array
my_array.slice(2) //returns a new array without modifying my_array

I'd like to make a new Array.prototype method that returns an array without modifying the array it was called upon. So this would be possible:

//[define new method here] Array.prototype.add_foo = function() {...
var my_array = ['poo'];

my_array.add_foo(); //would return ['poo', 'foo'];
my_array; //would return ['poo'];
2
  • Just clone the array first. Commented Aug 29, 2014 at 2:44
  • Okay, create a new array and return it instead of modifying this Commented Aug 29, 2014 at 2:45

2 Answers 2

10
my_array.concat('foo');

concat doesn't alter the original array.

Sign up to request clarification or add additional context in comments.

Comments

2
Array.prototype.add_foo = function(){
    var ret = this.slice(0); //make a clone
    ret.push("foo"); //add the foo
    return ret; //return the modified clone
}

3 Comments

Simpler: return this.concat('foo')
@elclanrs : Good. I've never used/spotted .concat. Thx
For some reason I had the impression I could only return a modified version of the original array and not a new instance of Array. thanks

Your Answer

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.