I have a array of objects, looks like
[
{Time: , //time stamp
psi: //pressure value at the time
},
... //other objects in the array the same
]
The array is named "data"
if I slice part of the array, and pass them to find local max and min values, would the code below deep copy and return the local extremes? How to verify?
var extreme = findLocalExtreme(data.slice(0, 10)); //slice(0, 10) for example, shallow copy
function findLocalExtreme(slicedArr){
//error control skipped, the array could be empty or only 1 member
let tempMax = slicedArr[0]; //would the "=" deep copy the object or just shallow copy?
let tempMin = slicedArr[0];
let slicedArrLength = slicedArr.length;
for (let i = 1; i < slicedArrLength; i++){
if (slicedArr[i].psi > tempMax.psi){
tempMax = slicedArr[I]; //deep copy or shallow copy?
}
if (slicedArr[i].psi < tempMin.psi){
tempMin = slicedArr[i];
}
}
return {
Max: tempMax,
Min: tempMin //is the value assignment in returned class deep copy, or still shallow copy?
}
}
Any advise welcome.
let tempMax = slicedArr[0]
will just do the shallow copy instead you can do let tempMax = {...slicedArr[0]}
since your object is only at level one this will do a deepcopy, if it is nested you can use loadash's cloneDeep to do a deepcopy.
Anywhere you are assiging a object to a variable it is a shallow copy
You can use loadsh
cloneDeep
method to copy objects or array.
import _ from 'loadsh';
let arr = [
{name: 'temp'}
{name: 'temp1}
]
let copyArr = _.cloneDeep(arr);
Deep Copy of a nested array of objects using JSON.parse(JSON.stringify(your_array_here))
reference link Deep Copy & Shallow Copy
//Deep Clone let a = [{ x:{z:1}, y: 2}]; let b = JSON.parse(JSON.stringify(a)); b[0].xz=0 console.log(a); console.log(b);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.