Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda