Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
How to insert an object into a specific index. Splice is not working for me

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!