-1

I have array with objects codeData, and I want to make array with arrays(in every array 3 objects) , and I made something like that:

let codeData = [{el: 1}, {el: 2} , {el: 3}, {el: 4}, {el: 5}, {el: 6}]
let arr = [...Array(Math.ceil(codeData.length / 3))].map(_ => codeData.splice(0, 3))

console.log(arr)

But it caused this error. How I can solve this?

adiga
  • 34,372
  • 9
  • 61
  • 83
  • The `codeData`'s `0` property is read-only, that's pretty clear. Please show its actual definition! – FZs Feb 17 '21 at 10:11
  • 1
    your code worked in the browser's console – malarres Feb 17 '21 at 10:12
  • @FZs this is data which I've got from BE. But I'm using React and codeDate is passed by props, could it be the reason of error? – wefwef цуаefwef Feb 17 '21 at 10:13
  • Not the way of passing, but rather its origin. It was made read-only either by the code that passed it or was constructed read-only somehow. – FZs Feb 17 '21 at 11:11

2 Answers2

0

You can use something like lodash chunk to achieve this easily

let codeData = [{el: 1}, {el: 2} , {el: 3}, {el: 4}, {el: 5}, {el: 6}]

let arr = _.chunk(codeData,3);

console.log(arr) will output

[[{el: 1}, {el: 2} , {el: 3}],[{el: 4}, {el: 5}, {el: 6}]]
Risalat Zaman
  • 1,189
  • 1
  • 9
  • 19
-1

you can try this without using any additional library:

    const newArray = [];
    const codeData = [{ el: 1 }, { el: 2 }, { el: 3 }, { el: 4 }, { el: 5 }, { el: 6 }];

    for (let i = 0; i < codeData.length; i++) {
        if (i % 3 === 1) {
            newArray.push([codeData[i-1], codeData[i], codeData[i + 1]]);
        }
    }
    console.log(newArray);
Ehsan
  • 188
  • 12
  • 1
    This is another way of [creating chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks). What is wrong with OP's code and how does it cause the error? – adiga Feb 17 '21 at 10:23