Home > Software design >  React native Array Sort problem when 2 array are the same value
React native Array Sort problem when 2 array are the same value

Time:12-14

I have a problem when I using the array sort function

I have 2 state value are saving the same array value, (devName and devNameSort)

I want to sorting the one of the array and try to get the index on the original array. However, when I sorting the array "devNameSort", the "devName" would be changed together. Would any method to fix the problem

The Value of
dev  = \["08d5", "151e", "d467", "0655", "a853"\]
devName = \["W1", "W4", "W2", "W3", "W0"\]
devNameSort = \["W1", "W4", "W2", "W3", "W0"\]
 this.state = {
            dev: this.props.route.params.dev,
            devName: this.props.route.params.devName, 
            devNameSort: this.props.route.params.devNameSort,
  }



    componentDidMount() {
        const sd = this.state.dev
        const sdn = this.state.devName
        console.log(sd);
        console.log(sdn);
        setTimeout( ()=> {
            const sdbs = this.state.devSort;
            console.log(sdn);
            sdbs.sort().map( (bs,index) => {
                const sdIndex = sdn.indexOf(bs)
                console.log(bs,":",index, sdIndex)
                console.log(sd[sdIndex])

            })
        }, 1000);
}
Expect result OutPut
LOG ["W1", "W4", "W2", "W3", "W0"] LOG ["W1", "W4", "W2", "W3", "W0"]
LOG W0 : 0 0 LOG W0 : 0 4
LOG 08d5 LOG a853
LOG W1 : 1 1 LOG W1 : 1 0
LOG 151e LOG 08d5
LOG W2 : 2 2 LOG W2 : 2 2
LOG d467 LOG d467
LOG W3 : 3 3 LOG W3 : 3 3
LOG 0655 LOG 0655
LOG W4 : 4 4 LOG W4 : 4 1
LOG a853 LOG 151e

CodePudding user response:

The same variable is passed as props. Make a copy of one of the arrays before sorting.

const sdn = [...this.state.devName]

CodePudding user response:

In javascript arrays and objects are mutable. you have to create copies of them for immutable behavior. One way is by using spread operator.

const shallowCopy = [ ...originalArray ]
  • Related