Home > Back-end >  How to insert an object into a specific index. Splice is not working for me
How to insert an object into a specific index. Splice is not working for me

Time:07-09

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}]

CodePudding user response:

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);

CodePudding user response:

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

  • Related