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

131
Views
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 answers
Answer question

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 Report

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 Report

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 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!