Home > Net >  How would I sort a prop of an array of objects nondestructively Reactjs?
How would I sort a prop of an array of objects nondestructively Reactjs?

Time:11-21

So I am trying to sort alphabetically an array of objects nondestructively by using state, so I can also return the array back to its original arrangement. I've tried quite a few ways of copying the original array into a new array to sort: JSON methods to carry a deep copy of this.props.getDaycare.toddlers:

 constructor(){
        super()
        this.state = {
            newArray: []
        }
        
    }

    sort = () => {
        let initialArray = this.props.getDaycare.toddlers
        let copiedInitialArray = JSON.parse(JSON.stringify(initialArray));
        console.log(copiedInitialArray)
        this.setState({
                newArray: copiedInitialArray.sort((t,u) =>{
                if (t.name < u.name) {return -1;}
                if (t.name > u.name) {return 1;}
                return 0;
               })
        })
    
    }

That didn't seem to work. It did not update the DOM at all, but it did in the console (alphabetically) when I clicked the sort button

0: {id: 84, name: 'Jared Leno', birthday: '2019-09-02', contact: 'Poppy Roberts', phone: 7605551919, …}
1: {id: 88, name: 'Massimo Gandolfini', birthday: '2019-01-06', contact: 'Poppy Roberts', phone: 7605551919, …}
2: {id: 87, name: 'Rosie Perez', birthday: '2018-12-22', contact: 'Poppy Roberts', phone: 7605559091, …}
3: {id: 80, name: 'Samantha Madison', birthday: '2019-01-06', contact: 'Olusoji Akinremi', phone: 7605551919, …}
4: {id: 90, name: 'Sara Waters', birthday: '2018-12-22', contact: 'Jessica Smith', phone: 7605559091, …}
5: {id: 83, name: 'Serena Williams', birthday: '2019-01-06', contact: 'Sara Reynolds', phone: 7605551919, …}
length: 6
[[Prototype]]: Array(0)

I've tried the shallow copying methods as well such as spread, slice, from. Noting but the same result of not updating the DOM but outputting in the console. I've looked everywhere online for this specific issue and I haven't seen any example showing how to effectively deep copy an array of objects for sorting. All the examples were destructive to the original array.

I'm wondering is there any way at all? please help.

CodePudding user response:

  1. To copy a JS Array, you can use Edit little-dream-6nig5

  • Related