Search code examples
javascriptarraysreactjscopyjavascript-objects

Clone an array and make it unique - Javascript


I have a problem. I have an array of objects. I need to make a copy out of it and make it unique, so when I modify my new array, it doesn't change anything in the original one.

I have tried the following:

let excelData = [...this.state.tableData]; 
let excelData = this.state.tableData.slice();
let excelData = this.state.tableData.concat();
let excelData = Array.from(this.state.tableData);

But all of the previously listed methods also modify the original array.

Here is my function:

addDynamicExcelColumns() {
        let excelData = [...this.state.tableData];
        if (this.state.compRentAttr.length > 0) {
            excelData.map((d, idx) => {
                this.state.compRentAttr.map((i, idx1) => {
                    excelData[idx][i.AttrName] = d.optionalAttributes[idx1];
                });
            });
        }
        return excelData;
    }

Solution

  • It is because you are just making a new array with same elements. when you do let excelData = [...this.state.tableData];, excelData[index] is equal to this.state.tableData[index]

    So, what you need to do is a deep clone. And it's not a perfect way to deep clone, but it looks like you can just use let excelData = JSON.parse(JSON.stringify(this.state.tableData));.