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

140
Vistas
what's wrong with this sort function? javascript

I want to find out the index of the element which is the lowest number in the array. For ex: function getIndexToIns([3, 2, 10, 7], 4) will return 2 because if 4 is inserted into the array, the array should be [2, 3, 4, 7, 10] following ascending order. And 4 has the index of 2.

And my code snippet is as below and it shows error "TypeError: newArr.sort is not a function"

function getIndexToIns(arr, num) {
newArr = arr.push(num);
newArr.sort((a, b) => a-b);
return newArr.indexOf(num)
}

getIndexToIns([2, 10, 4], 50);
console.log(getIndexToIns([2, 10, 4], 50))

What is wrong in my code snippet???

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

.push() modifies the array in place, it does not return a new array. So newArray isn't an array.

You can create a new array with something like:

let newArr = [...arr, num];

Or perhaps:

let newArr = arr.concat([num]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Welcome.

Remove newArr in newArr = arr.push(num); to become

arr.push(num);

Push method doesn't return the array itself but the new length. Ref

about 4 years ago · Juan Pablo Isaza Denunciar

0

See documentation for Array.prototype.push():

The push() method adds one or more elements to the end of an array and returns the new length of the array.

On top of that, push and sort methods mutate your original array. You should define your newArr like this:

const newArr = [...arr, num];

Then you can sort it and find out the index of element like you do it now.

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