0

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.

3 Answers 3

4

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

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

Comments

2

You can use loadsh cloneDeep method to copy objects or array.

import _ from 'loadsh';
let arr = [
            {name: 'temp'}
            {name: 'temp1}
       ]

let copyArr = _.cloneDeep(arr);

Comments

0

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].x.z=0
console.log(a);
console.log(b); 

Comments

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.