Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an array without a removed element? Using splice() without changing the array?

I want to do something like:

var myArray = ["one","two","three"]; document.write(myArray.splice(1,1)); document.write(myArray); 

So that it shows first "one,three", and then "one,two,three". I know splice() returns the removed element and changes the array, but is there function to return a new array with the element removed? I tried:

window.mysplice = function(arr,index,howmany){     arr.splice(index,howmany);     return arr;    }; 

If I try:

var myArray = ["one","two","three"]; document.write(mySplice(myArray,1,1)); document.write(myArray); 

It still changes myArray.

like image 802
mowwwalker Avatar asked Jul 26 '11 03:07

mowwwalker


People also ask

Does splice returns removed element?

Yes, splice returns the removed items, and the output is supposed to be a because that's what you removed.

What is the use of splice () method returns a section of an array?

The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.

Does splice method return a new array?

The splice() method returns the removed items in an array. The slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.


1 Answers

You want slice:

Returns a one-level deep copy of a portion of an array.

So if you

a = ['one', 'two', 'three' ]; b = a.slice(1, 3); 

Then a will still be ['one', 'two', 'three'] and b will be ['two', 'three']. Take care with the second argument to slice though, it is one more than the last index that you want to slice out:

Zero-based index at which to end extraction. slice extracts up to but not including end.

like image 139
mu is too short Avatar answered Oct 15 '22 03:10

mu is too short