-1

I am passing an array to a function. Since, in javascript, arrays by default get passed by reference I tried to make a copy of array. But in the end, the operations performed in function effects the actual array data.

All I want to do is save the actual state of an array.

Here is my code :

let  arrcopy =new Array( items.dt);
citem = binarySearch(arrcopy[0], ind.ItemID);
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
Ricky
  • 114
  • 1
  • 10
  • My glassball's best guess is you want to deep copy an array, but from the code and text given, i can't really be sure at all. – ASDFGerte Jul 17 '18 at 11:55
  • 2
    Possible duplicate of [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – sjahan Jul 17 '18 at 11:58
  • Yes i want a deep copy of an array i am using an object array of items sending those to binary search method – Ricky Jul 17 '18 at 12:03
  • when i get result from method there is only one item remaining in orignal items array – Ricky Jul 17 '18 at 12:04

3 Answers3

0

You means you want to preserve the original array as it is (you want to preserve immutability)?

Then use reduce method.

    const test = (arr) => {
    return arr.reduce((result, val) => {
       // do the needful here
      result.push(val);
      return result;
    }, []);
}

expect(arr).to.be.equal(result); => will return false as the original array won't be updated

achini
  • 419
  • 4
  • 7
0

You will need to create array as copy with Object.assign

let  arrcopy = Object.assign([],items.dt);
citem = binarySearch(arrcopy[0], ind.ItemID);

Or just ES6 way with destruction/spread operator is enough

let arrcopy = [...items.dt];
Manoz
  • 6,507
  • 13
  • 68
  • 114
0
JSON.parse(JSON.stingify(items.dt))

this has made my work

Ricky
  • 114
  • 1
  • 10