0

How are 2d arrays cloned using json.stringify and json.pasrse ?I came across this function which does but couldn't get the technique.What are some other methods to achieve the same?

Note: The JSON.stringify() method converts a JavaScript value to a JSON string.

let g2 = arrayclone(this.state.gridfull);// note gridfull is 2d array 
        function arrayclone(arr) {
        return JSON.parse(JSON.stringify(arr));
}
2
  • 1
    JSON.parse(JSON.stringify(arr)) is a usual method to clone any kind of object or array: You convert it to a string and back to a new object/array Commented Jan 25, 2018 at 23:52
  • 1
    oh . i see being new to reactjs and javascript ,it looked alien concept to me . Commented Jan 25, 2018 at 23:54

1 Answer 1

4

You could use ES6 deestructurtig:

[...arr]

Or you could you Array.from:

Array.from(arr)

Or you could use concat:

[].concat(arr)

Or you could use slice:

arr.slice()
arr.slice(0)

You could create an empty array and iterate over your original one pushing elements to the new one.

I think that's pretty much it.

Hope it helps.

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

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.