skip to Main Content

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);
}
OutPut Expect result
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

——— 14/12/2022 update ———

I updated the code as const a copy, but it not work too

        const sdn = this.state.devName
        const sdCopy = this.state.devName
        console.log("Orginal - before sort", sdn);
        sdn.sort()
        console.log("Orginal", sdn);
        console.log("Copy", sdCopy);

 LOG  Orginal - before sort ["W4", "W1", "W3"]
 LOG  Orginal ["W1", "W3", "W4"]
 LOG  Copy ["W1", "3", "W4"]

I Find the solution, but don’t understand why it work.

const sdn = this.state.devName 
const sdCopy = JSON.parse(JSON.stringify(sdn))
sdCopy.sort().map((bs,index) => {
                const sdIndex = this.state.devName.indexOf(bs)
                console.log(bs,":",index, sdIndex)
                console.log(sd[sdIndex])
            })

2

Answers


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

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

    Login or Signup to reply.
  2. 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 ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search