-2

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

  • 1
    [arr.push(num)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) returns a number, not an array – Nicholas Tower Oct 14 '21 at 14:19
  • The task you're trying to solve doesn't seem to require sorting at all. You can just count how many items of the array are less than `num`. That will be the index of `num` if it's inserted ordered. Of `[3, 2, 10, 7]` there are two items less than `4`. The index is thus `2`. – VLAZ Oct 14 '21 at 14:44
  • I figured. Thank you all so much! :)) – Aris Nguyen Oct 15 '21 at 12:05

3 Answers3

1

.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]);
David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    You don't need to wrap `num` in an array to `concat()`. Also, it wouldn't need to return a new array (if it returned an array at all), it could return the same array (as Map.set() returns the Map after setting), but the main point is it returns the new length of the array after pushing. – pilchard Oct 14 '21 at 14:21
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

Thanh Trung
  • 3,566
  • 3
  • 31
  • 42
  • 1
    This is unacceptable because it will modify the original array. – Maksym Shcherban Oct 14 '21 at 14:23
  • 1
    @MaxScherban I don't see anything in the question that says the array shouldn't be modified. – VLAZ Oct 14 '21 at 14:42
  • @MaksymShcherban This is up to the developer if he wishes to modify the array or not. Agree that this is not fully the whole answer, I only point out the main reason why he has a `TypeError` – Thanh Trung Oct 15 '21 at 09:27
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.

Maksym Shcherban
  • 742
  • 4
  • 13