JAVA SCRIPT ARRAY - Extracting a Portion of an Array

 Extracting a Portion of an Array


You want to extract out a portion of an array but keep the original array intact. 


The Array slice() method extracts a shallow copy of a portion of an existing array: 

var animals = ['elephant','tiger','lion','zebra','cat','dog','rabbit','goose'];
var domestic = animals.slice(4,7);
console.log(domestic); // ['cat','dog','rabbit'];


The slice() makes a copy of a portion of an existing array, returning a new array. It makes a shallow copy, which means that if the array elements are objects, both arrays point to the same object—modifications to the object in the new array is reflected in the same object in the old array. In the following, slice() is used on an array of array elements to extract out of the arrays. The contents are modified and both arrays are printed out. The changes to the new array are reflected in the old:

var mArray = [];
mArray[0] = ['apple','pear'];
mArray[1] = ['strawberry','lemon'];
mArray[2] = ['lime','peach','berry'];
var nArray = mArray.slice(1,2);
console.log(mArray[1]); // ['strawberry','lemon']
nArray[0][0] = 'raspberry';
console.log(nArray[0]); // ['raspberry','lemon']
console.log(mArray[1]); // ['raspberry','lemon']

The values are copied by reference. If the array element is a primitive data type, such as a string or number, the elements are copied by value—changes to the new array won’t be reflected in the old.


Post a Comment