1

I tried replacing my elements specifically with an object. But it is just adding up like a push and making the array longer.

let arr = [];

function addToArray(index){
    let comment = value;
    let score= scoreType;
    let scorenow = score;
    let id = id;

    arr.splice(index,0,{comment,score,scorenow ,id });
}

I am figuring out a way to insert this object only to the index of arr.

Example : addToArray(2) should return a [undefined,undefined,{comment,score,scorenow,id}]

Ryuzaki
  • 144
  • 2
  • 10
  • Does this answer your question? [How to insert an item into an empty array at a specific index?](https://stackoverflow.com/questions/54038872/how-to-insert-an-item-into-an-empty-array-at-a-specific-index) – Arman P. Jul 08 '22 at 16:52
  • 2
    Splice doesn't work that way, it only adds to existing spaces or to the end of the array. You can manually increase its length and fill it with `undefined` – Eldar B. Jul 08 '22 at 16:53
  • Incidentally, where are `value`, `scoreType`, `id`, and `score` coming from? – Andy Jul 08 '22 at 16:55
  • Also, why not just push the object into the array and then, if you need to locate it, use `find` or `findIndex` on the array to identify the object by `id`. – Andy Jul 08 '22 at 17:00

2 Answers2

2

You can use this syntax:

let arr = [];

function addToArray(index){
    let comment = 1;
    let score= 2;
    let scorenow = 3;
    let id = 4;

    arr[index] = { comment, score, scorenow, id };
}

addToArray(2);

console.log(arr);

If you want to do it with splice method you have to define the arr length first:

let arr = [];

function addToArray(index){
    let comment = 1;
    let score= 2;
    let scorenow = 3;
    let id = 4;

    arr.length = index;
    arr.splice(index, 0, { comment, score, scorenow, id });
}

addToArray(2);

console.log(arr);
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
-1

try this instead :

arr.splice(index,1,{comment,score,scorenow ,id });

putting 1 instead of 0 will replace the specific element , not appending a new one