0

I'm developing an app with react native. I have an array of object in the state (lettersPosition) and I want to sort it temporally in a variable within a function (but I don't want the state itself to be sorted) :

verifyWord = () => {
    const array = this.state.lettersPosition;       
    array.sort(function (a, b) {
        return a.x - b.x;
    });
    var word = "";
    array.map(function (char) {
        word += char.letter
    })
}

I tested it and it appears that my state itself was updated after the sorting (even if I called the sort function on the temp array).

It is like if the 'array' variable contains the whole reference to the state and not only its value. And if I modify that variable, it modifies the state too.

Is it a normal behaviour in react ?

How can I just get the value of the state and manipulate it without changing the state itself ?

Thanks

kikdu
  • 9
  • 2

3 Answers3

0

Try using var newArray = oldArray.slice(); rather than const array = this.state.lettersPosition; In your code you're not creating a copy of the array, you're just assigning it to another variable.

See Copy array by value for more info on var newArray = oldArray.slice();.

Tonis F. Piip
  • 776
  • 2
  • 6
  • 16
0

Use Array.from(). It creates a shallow copy.

const sortedArray = Array.from(this.state.lettersPosition);
...etc
Matt Carlotta
  • 18,972
  • 4
  • 39
  • 51
0

You can use the spread operator too.

var a = [1, 2, 3, 4, 5]
var b = [...a]
sridhar
  • 612
  • 5
  • 12