Extract Multiple Items of an Array in JavaScript


Let’s see how we can extract items from an array without affecting the original array in JavaScript. We will use the array slice() method to extracts a shallow copy of a portion of an existing array:

let fruits = ['orange','banana','mango','cherry','strawberry','apple'];

let fvrtFruits = fruits.slice(1,4);

console.log(fvrtFruits); // ['banana','mango','cherry','strawberry'];

The slice() method in javascript 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:

let fruitsArray = [];
fruitsArray[0] = ['mango','pear'];
fruitsArray[1] = ['strawberry','lemon'];
fruitsArray[2] = ['lime','peach','berry'];

var nArray = mArray.slice(1,2);
console.log(mArray[1]); // ['strawberry','lemon']

nArray[0][0] = 'banana';
console.log(nArray[0]); // ['banana','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.

Leave a Reply

Your email address will not be published. Required fields are marked *